打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#同步网络时间

客户的机器的系统时间经常出错,导致给他们做的软件无法正常使用,所以后来就加了一个同步网络时间的小功能。实现起来很简单,但是却很使用。


这个小功能就是先获取网络时间,然后将系统的时间修改成从网络获得的时间。下面是具体的实现:


获取网络时间: 

  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.     }  

两个方法分别写在了两个类里面,只需要在客户端实例化两个对象,然后依次调用其方法即可,简单实用。

PS:Win8修改系统时间需要管理员的权限,下篇博客介绍如何让
程序默认以管理员权限运行,敬请期待!




本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
给shutdown.exe带个参数`!!新手求救!!
如何:将字符串转换为 DateTime(C# 编程指南)
C# List 根据对象属性去重的四种方法对比
简单介绍托管执行和 CLI
C#中的类型转换
C#中的类型转换 Gzu521.com我的学习网
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服