c#将电脑时间同步到网络时间
最近遇到个项目,需要控制软件使用时间,由于电脑不联网可以修改时间,故需要联网使电脑同步网络时间
网上寻找了很多解决方案,代码如下:
//Forproc_Win32.cs
//对常用Win32 API函数及结构的声明
using System;
using System.Runtime.InteropServices;
namespace Farproc.Win32
{
/// <summary>
///
/// </summary>
public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
/// <summary>
/// 从System.DateTime转换。
/// </summary>
/// <param name="time">System.DateTime类型的时间。</param>
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}
/// <summary>
/// 转换为System.DateTime类型。
/// </summary>
/// <returns></returns>
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
/// <summary>
/// 静态方法。转换为System.DateTime类型。
/// </summary>
/// <param name="time">SYSTEMTIME类型的时间。</param>
/// <returns></returns>
public static DateTime ToDateTime(SYSTEMTIME time)
{
return time.ToDateTime();
}
}
public class Win32API
{
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime( ref SYSTEMTIME Time );
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SYSTEMTIME Time);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
//取得当前系统时间
DateTime t = DateTime.Now;
//在当前时间上加上一周
t = t.AddDays(7);
//转换System.DateTime到SYSTEMTIME
SYSTEMTIME st = new SYSTEMTIME();
st.FromDateTime(t);
//调用Win32 API设置系统时间
Win32API.SetLocalTime(ref st);
//显示当前时间
MessageBox.Show(DateTime.Now.ToString());
}
试过很多次,都没能正确修改。
后来突发奇想,cmd不是能修改系统时间吗?
然后用cmd命令成功实现了功能。
/// <summary>
/// 获取网络日期时间
/// </summary>
/// <returns></returns>
public static string GetNetDateTime()
{
WebRequest request = null;
WebResponse response = null;
WebHeaderCollection headerCollection = null;
string datetime = string.Empty;
try
{
request = WebRequest.Create("https://www.baidu.com");
request.Timeout = 3000;
request.Credentials = CredentialCache.DefaultCredentials;
response = (WebResponse)request.GetResponse();
headerCollection = response.Headers;
foreach (var h in headerCollection.AllKeys)
{ if (h == "Date") { datetime = headerCollection[h]; } }
return datetime;
}
catch (Exception) { return datetime; }
finally
{
if (request != null)
{ request.Abort(); }
if (response != null)
{ response.Close(); }
if (headerCollection != null)
{ headerCollection.Clear(); }
}
}
//调用cmd修改系统时间
public static void setSystemTime(DateTime netTime)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = true;//不显示程序窗口
p.Start();//启动程序
string dtdate = netTime.ToString("yyyy-MM-dd");//获取日期
string dttime = netTime.ToString("HH:mm:ss");//获取时间
string dos1 = "date " + dtdate;//命令1
string dos2 = "time " + dttime;//命令2
p.StandardInput.WriteLine(dos1 + "&" + dos2 + "&exit");
p.StandardInput.AutoFlush = true;
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();//等待程序执行完退出进程
p.Close();
}
c#将电脑时间同步到网络时间的更多相关文章
- SYN2102型 NTP网络时间服务器
SYN2102型 NTP网络时间服务器 ntp主时钟服务器ntp时钟服务器厂商使用说明视频链接: http://www.syn029.com/h-pd-57-0_310_1_-1.html 请将 ...
- GPS校时器,GPS时钟装置,NTP网络时间服务器
GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间服务器 GPS校时器,GPS时钟装置,NTP网络时间 ...
- 配置NTP网络时间自动校对系统时间和创建备份文件
1 案例1:配置用户和组账号 1.1 问题 本例要求创建下列用户.组以及组的成员关系: 新建用户 alex,其用户ID为3456,密码是flectrag 创建一个名为 adminuser 的组 创建一 ...
- Linux服务器同步网络时间
Linux服务器运行久时,系统时间就会存在一定的误差,一般情况下可以使用date命令进行时间设置,但在做数据库集群分片等操作时对多台机器的时间差是有要求的,此时就需要使用ntpdate进行时间同步. ...
- linux系统时间与网络时间不同步
在解决问题之前,我们首先来了解下面几个知识点: 1. date命令: #date 显示系统时间 2.hwclock命令 (即hardwareclock系统硬件时间) #hwclock 显示硬件时间 ...
- SYN2136型 北斗NTP网络时间服务器
SYN2136型 北斗NTP网络时间服务器 北斗NTP网络时间服务器时间服务器使用说明视频链接: http://www.syn029.com/h-pd-109-0_310_36_-1.html 请将 ...
- SYN2101型 NTP网络时间服务器
SYN2101型 NTP网络时间服务器 时钟校准服务器时间 ntp服务器ntp时间校准服务器使用说明视频链接: http://www.syn029.com/h-pd-56-0_310_1_-1. ...
- 使用 NTP/Chrony 同时 Centos7 网络时间
Network Time Protocol(NTP)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,提供高精准度的时间校正服务. 在 Centos ...
- Linux实验:NTP网络时间服务器
[实验目的] 1)掌握时间服务器的搭建方法 2)掌握客户机与时间服务同步时间的方法[实验原理] NTP服务器[Network Time Protocol(NTP)]是用来使计算机时间 ...
随机推荐
- Jmeter Web 性能测试入门 (四):一个小实例带你学会 Jmeter 脚本编写
测试场景: 模拟并发100个user,在TesterHome 站内搜索VV00CC 添加线程组 添加HTTP信息头管理器 添加HTTP Sampler 填写HTTP Sampler中的信息 添加监听器 ...
- 转:C++何时调用构造函数,何时调用析构函数
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/wjf1997/article/detai ...
- SCRIPT438: 对象不支持“trim”属性或方法
关于ie9以下不支持trim()方法 可以在自己封装的框架中加入如下.或直接调用也行. if(!String.prototype.trim) { String.prototype.trim = fun ...
- np.random.choices的使用
在看莫烦python的RL源码时,他的DDPG记忆库Memory的实现是这样写的: class Memory(object): def __init__(self, capacity, dims): ...
- VScode优化记录
主题: One Dark Pro VS Code 官网页面 这是为 VS Code准备的 One Dark 主题,他是 Atom 标志性的主题.需要我说更多吗?我喜欢这个主题. Mon ...
- python Image 模块处理图片
Python-Image 基本的图像处理操作,有需要的朋友可以参考下. Python 里面最常用的图像操作库是 pip install Pillow #安装模块 from PIL import Ima ...
- Oracle查询显示CLOB的内容
select dbms_lob.substr(note) from table
- SpringBoot: 16.整合junit单元测试(转)
1.创建maven项目,修改pom.xml文件 <!--springboot项目依赖的父项目--> <parent> <groupId>org.springfram ...
- python基础--list
定义list-->l=[] stus=['张三','李四','王五'] list增删改查 #增 stus.append('狄仁杰')#增加---append在list末尾增加一个元素 stus. ...
- Ubuntu Docker-ce安装
使用官方给的脚本进行安装 curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun