当前位置: 移动技术网 > IT编程>开发语言>.net > C# 同步更新系统时间

C# 同步更新系统时间

2019年06月01日  | 移动技术网IT编程  | 我要评论

竞技者之极限酷跑,快枪手韦德,丁俊晖简历

前言

在定位用户问题时,发现有些电脑,会出现系统时间不是最新的问题。

可能原因:

  1. 取消了勾选服务器时间同步
  2. 当前安装的系统,是一个未知来源系统,导致系统时间更新失败

而系统时间不正确,会导致ie选项-证书,校验不通过~

更新系统时间

1. 连接时间服务器

时间服务器列表(推荐): string[] timehosts = { "time.windows.com", "time.nist.gov" };

 1     /// <summary>
 2     /// 连接时间服务器
 3     /// </summary>
 4     /// <param name="socket">服务器接口</param>
 5     /// <param name="starttime">开始时间</param>
 6     /// <param name="errormsg">错误信息</param>
 7     /// <returns></returns>
 8     private static bool tryconnecttotimeserver(out socket socket, out datetime starttime, out string errormsg)
 9     {
10         socket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);//创建socket   
11         socket.receivetimeout = 10 * 1000;//设置超时时间   
12         errormsg = string.empty;
13         starttime = datetime.now;
14 
15         // 遍历时间服务器列表   
16         foreach (string strhost in timehosts)
17         {
18             try
19             {
20                 // 记录开始的时间   
21                 starttime = datetime.now;
22 
23                 var iphostinfo = dns.gethostentry(strhost);
24                 var ip = iphostinfo.addresslist[0];
25                 //建立ipaddress对象与端口,创建ipendpoint节点:   
26                 int port = 13;
27                 var ipe = new ipendpoint(ip, port);
28                 //连接到服务器   
29                 socket.connect(ipe);
30                 // 如果连接到服务器就跳出  
31                 if (socket.connected) break;
32             }
33             catch (exception ex)
34             {
35                 errormsg = $"时间服务器连接失败!\r\n错误信息:{ex.message}系统提示";
36             }
37         }
38         return socket.connected;
39     }

2. 从服务器接收数据

 1     /// <summary>
 2     /// 从服务器接收数据
 3     /// </summary>
 4     /// <param name="socket"></param>
 5     /// <returns></returns>
 6     private static stringbuilder receivemessagefromserver(socket socket)
 7     {
 8         //socket同步接受数据   
 9         byte[] receivebytes = new byte[1024];
10         int nbytes, ntotalbytes = 0;
11         stringbuilder sb = new stringbuilder();
12         system.text.encoding encoding = encoding.utf8;
13 
14         while ((nbytes = socket.receive(receivebytes, 0, 1024, socketflags.none)) > 0)
15         {
16             ntotalbytes += nbytes;
17             sb.append(encoding.getstring(receivebytes, 0, nbytes));
18         }
19 
20         return sb;
21     }

3. 更新本地时间

 1     /// <summary>
 2     /// 更新系统时间
 3     /// </summary>
 4     /// <returns>更新结果</returns>
 5     public static string updatesystemtime()
 6     {
 7         try
 8         {
 9             var connected = tryconnecttotimeserver(out socket socket, out var starttime, out string errormsg);
10             if (connected)
11             {
12                 var receivedmsg = receivemessagefromserver(socket);
13                 socket.close();
14                 //切割字符串 
15                 string[] receivemsglist = receivedmsg.tostring().split(' ');
16                 if (receivemsglist.length >= 3)
17                 {
18                     var datetimevalue = receivemsglist[1] + " " + receivemsglist[2];
19                     setlocaltime(starttime, datetimevalue);
20                 }
21             }
22             else
23             {
24                 return errormsg;
25             }
26         }
27         catch (exception e)
28         {
29             return $"函数{nameof(updatesystemtime)}执行异常,{e.message}";
30         }
31         return "时间已同步";
32     }
33     /// <summary>
34     /// 设置系统时间
35     /// </summary>
36     /// <param name="starttime">请求服务器时的开始时间</param>
37     /// <param name="datetimevalue">服务器返回的时间</param>
38     private static void setlocaltime(datetime starttime, string datetimevalue)
39     {
40         // 得到开始到现在所消耗的时间 
41         timespan k = datetime.now - starttime;
42         // 减去中途消耗的时间
43         datetime updatedutctime = convert.todatetime(datetimevalue).subtract(-k);
44 
45         //处置北京时间 +8时   
46         var updatedtime = updatedutctime.addhours(8);
47 
48         //转换system.datetime到systemtime   
49         systemtime systemtime = new systemtime();
50         systemtime.fromdatetime(updatedtime);
51 
52         //调用win32 api设置系统时间   
53         win32api.setlocaltime(ref systemtime);
54     }

系统时间辅助类 & win32api :

 1     /// <summary>
 2     /// 系统时间帮助类
 3     /// </summary>
 4     public struct systemtime
 5     {
 6         public ushort wyear;
 7         public ushort wmonth;
 8         public ushort wdayofweek;
 9         public ushort wday;
10         public ushort whour;
11         public ushort wminute;
12         public ushort wsecond;
13         public ushort wmilliseconds;
14 
15         /// <summary>
16         /// 从system.datetime转换。
17         /// </summary>
18         /// <param name="time">system.datetime类型的时间。</param>
19         public void fromdatetime(datetime time)
20         {
21             wyear = (ushort)time.year;
22             wmonth = (ushort)time.month;
23             wdayofweek = (ushort)time.dayofweek;
24             wday = (ushort)time.day;
25             whour = (ushort)time.hour;
26             wminute = (ushort)time.minute;
27             wsecond = (ushort)time.second;
28             wmilliseconds = (ushort)time.millisecond;
29         }
30         /// <summary>
31         /// 转换为system.datetime类型。
32         /// </summary>
33         /// <returns></returns>
34         public datetime todatetime()
35         {
36             return new datetime(wyear, wmonth, wday, whour, wminute, wsecond, wmilliseconds);
37         }
38         /// <summary>
39         /// 静态方法。转换为system.datetime类型。
40         /// </summary>
41         /// <param name="time">systemtime类型的时间。</param>
42         /// <returns></returns>
43         public static datetime todatetime(systemtime time)
44         {
45             return time.todatetime();
46         }
47     }
48 
49     /// <summary>
50     /// 系统更新时间dll
51     /// </summary>
52     public class win32api
53     {
54         [dllimport("kernel32.dll")]
55         public static extern bool setlocaltime(ref systemtime time);
56         [dllimport("kernel32.dll")]
57         public static extern void getlocaltime(ref systemtime time);
58     }

 

github地址:ie环境修复工具

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网