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)]是用来使计算机时间 ...
随机推荐
- Windows下使用cmd运行jar文件
一般window系统下是不能直接运行jar文件的.(有些电脑可以,记得我以前的电脑是双击jar就可以运行的) 那么如何在windows下运行jar呢? 1.首先,电脑必须配置java运行环境jre-- ...
- ubuntu hadoop安装
参考: https://wangchangchung.github.io/2017/09/28/Ubuntu-16-04%E4%B8%8A%E5%AE%89%E8%A3%85Hadoop%E5%B9% ...
- python获取当前py文件的文件名或者当前工具箱的名字
#########################import arcpy import osimport sys ########################################## ...
- kotlin 泛型中类型投射
fun main(arg: Array<String>) { var ints:Array<Int> = arrayOf(, , ) val any =Array<Any ...
- python之Anaconda python3.7安装
1.下载 https://www.anaconda.com/distribution/ #你会发现,使用windows下载十分慢,既然这样,为何不尝试centos(linux)安装呢?本人使用cent ...
- NIO单一长连接——dubbo通信模型实现
转: NIO单一长连接——dubbo通信模型实现 峡客 1.2 2018.07.15 19:04* 字数 2552 阅读 6001评论 30喜欢 17 前言 前一段时间看了下dubbo,原想将dubb ...
- PostgreSql 使用自定义序列(Sequence)向表插入数据
最近公司使用到了PostgreSql,哈哈,这个SQL之前基本上没有用过,既然公司使用到了,那就学习一下吧,记一篇小笔记: 什么是PostgreSql:https://www.postgresql.o ...
- BTE的一些知识
1.今天遇到一个问题,看项目上做了BTE增强00001120 事件的BTE 但是自定义函数 更改了参数 t_bseg t_bkpf MODIFY t_bkpf FROM ls_bkpf TRAN ...
- .NET Core微服务架构学习与实践系列文章索引目录
一.为啥要总结和收集这个系列? 今年从原来的Team里面被抽出来加入了新的Team,开始做Java微服务的开发工作,接触了Spring Boot, Spring Cloud等技术栈,对微服务这种架构有 ...
- flask上下文管理相关 - threading.local 以及原理剖析
threading.local 面向对象相关: setattr/getattr class Foo(object): pass obj = Foo() obj.x1 = 123 # object.__ ...