1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Net; 7 using System.Net.Sockets; 8 using System.Text.RegularExpressions; 9 using System.Runtime.InteropServices; 10 using System.Runtime; 11 12 13 14 /// <summary> 15 /// 網絡時間 16 /// </summary> 17 public class NetTime 18 { 19 20 /// <summary> 21 /// 獲取標准北京時間,讀取http://www.beijing-time.org/time.asp 22 /// </summary> 23 /// <returns>返回網絡時間</returns> 24 public DateTime GetBeijingTime() 25 { 26 27 DateTime dt; 28 WebRequest wrt = null; 29 WebResponse wrp = null; 30 try 31 { 32 wrt = WebRequest.Create("http://www.beijing-time.org/time.asp"); 33 wrp = wrt.GetResponse(); 34 35 string html = string.Empty; 36 using (Stream stream = wrp.GetResponseStream()) 37 { 38 using (StreamReader sr = new StreamReader(stream, Encoding.UTF8)) 39 { 40 html = sr.ReadToEnd(); 41 } 42 } 43 44 string[] tempArray = html.Split(';'); 45 for (int i = 0; i < tempArray.Length; i++) 46 { 47 tempArray[i] = tempArray[i].Replace("\r\n", ""); 48 } 49 50 string year = tempArray[1].Split('=')[1]; 51 string month = tempArray[2].Split('=')[1]; 52 string day = tempArray[3].Split('=')[1]; 53 string hour = tempArray[5].Split('=')[1]; 54 string minite = tempArray[6].Split('=')[1]; 55 string second = tempArray[7].Split('=')[1]; 56 57 dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second); 58 } 59 catch (WebException) 60 { 61 return DateTime.Parse("2011-1-1"); 62 } 63 catch (Exception) 64 { 65 return DateTime.Parse("2011-1-1"); 66 } 67 finally 68 { 69 if (wrp != null) 70 wrp.Close(); 71 if (wrt != null) 72 wrt.Abort(); 73 } 74 return dt; 75 76 } 77 }
獲取網絡時間,返回一個DateTime對象,然后傳給設置系統時間的方法,修改系統時間。下面是設置系統時間的代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Net; 7 using System.Net.Sockets; 8 using System.Text.RegularExpressions; 9 using System.Runtime.InteropServices; 10 using System.Runtime; 11 12 13 /// <summary> 14 /// 更新系統時間 15 /// </summary> 16 public class UpdateTime 17 { 18 //設置系統時間的API函數 19 [DllImport("kernel32.dll")] 20 private static extern bool SetLocalTime(ref SYSTEMTIME time); 21 22 [StructLayout(LayoutKind.Sequential)] 23 private struct SYSTEMTIME 24 { 25 public short year; 26 public short month; 27 public short dayOfWeek; 28 public short day; 29 public short hour; 30 public short minute; 31 public short second; 32 public short milliseconds; 33 } 34 35 /// <summary> 36 /// 設置系統時間 37 /// </summary> 38 /// <param name="dt">需要設置的時間</param> 39 /// <returns>返回系統時間設置狀態,true為成功,false為失敗</returns> 40 public static bool SetDate(DateTime dt) 41 { 42 SYSTEMTIME st; 43 44 st.year = (short)dt.Year; 45 st.month = (short)dt.Month; 46 st.dayOfWeek = (short)dt.DayOfWeek; 47 st.day = (short)dt.Day; 48 st.hour = (short)dt.Hour; 49 st.minute = (short)dt.Minute; 50 st.second = (short)dt.Second; 51 st.milliseconds = (short)dt.Millisecond; 52 bool rt = SetLocalTime(ref st); 53 return rt; 54 } 55 }
需要注意的時,在win8系統上需要以管理員身份來運行程序,否則是無法設置系統時間的。下面這段代碼可以設置讓程序默認以管理員身份運行:
1 static void Main(string[] Args) 2 { 3 /** 4 * 當前用戶是管理員的時候,直接啟動應用程序 5 * 如果不是管理員,則使用啟動對象啟動程序,以確保使用管理員身份運行 6 */ 7 //獲得當前登錄的Windows用戶標示 8 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); 9 //創建Windows用戶主題 10 Application.EnableVisualStyles(); 11 12 System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); 13 //判斷當前登錄用戶是否為管理員 14 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) 15 { 16 //如果是管理員,則直接運行 17 18 Application.EnableVisualStyles(); 19 Application.Run(new Form1()); 20 } 21 else 22 { 23 //創建啟動對象 24 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 25 //設置運行文件 26 startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; 27 //設置啟動參數 28 startInfo.Arguments = String.Join(" ", Args); 29 //設置啟動動作,確保以管理員身份運行 30 startInfo.Verb = "runas"; 31 //如果不是管理員,則啟動UAC 32 System.Diagnostics.Process.Start(startInfo); 33 //退出 34 System.Windows.Forms.Application.Exit(); 35 } 36 }
搞定!