天天看點

C# 同步更新系統時間

前言

在定位使用者問題時,發現有些電腦,會出現系統時間不是最新的問題。

可能原因:

  1. 取消了勾選伺服器時間同步
  2. 目前安裝的系統,是一個未知來源系統,導緻系統時間更新失敗
C# 同步更新系統時間

而系統時間不正确,會導緻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      

View Code

Github位址:​​IE環境修複工具​​

作者:唐宋元明清2188

本文版權歸作者所有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連接配接,否則保留追究法律責任的權利。

繼續閱讀