好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#同步网络时间

C#同步网络时间

C#同步网络时间

 

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

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

获取网络时间: 

 using   System;  
  using   System.Collections.Generic;  
  using   System.Linq;  
  using   System.Text;  
  using   System.IO;  
  using   System.Net;  
  using   System.Net.Sockets;  
  using   System.Text.RegularExpressions;  
  using   System.Runtime.InteropServices;
  using   System.Runtime;    



      ///   <summary>   
     ///   网络时间  
      ///   </summary>   
     public   class   NetTime
    {
       
          ///   <summary>   
         ///   获取标准北京时间,读取http://HdhCmsTestbeijing-time.org/time.asp  
          ///   </summary>   
         ///   <returns>  返回网络时间  </returns>   
         public   DateTime GetBeijingTime()
        {
         
            DateTime dt;
            WebRequest wrt  =  null  ;
            WebResponse wrp  =  null  ;
              try  
            {
                wrt  = WebRequest.Create( "  http://HdhCmsTestbeijing-time.org/time.asp  "  );
                wrp  =  wrt.GetResponse();

                  string  html =  string  .Empty;
                  using  (Stream stream =  wrp.GetResponseStream())
                {
                      using  (StreamReader sr =  new   StreamReader(stream, Encoding.UTF8))
                    {
                        html  =  sr.ReadToEnd();
                    }
                }

                  string [] tempArray = html.Split( '  ;  '  );
                  for  ( int  i =  0 ; i < tempArray.Length; i++ )
                {
                    tempArray[i]  = tempArray[i].Replace( "  \r\n  " ,  ""  );
                }

                  string  year = tempArray[ 1 ].Split( '  =  ' )[ 1  ];
                  string  month = tempArray[ 2 ].Split( '  =  ' )[ 1  ];
                  string  day = tempArray[ 3 ].Split( '  =  ' )[ 1  ];
                  string  hour = tempArray[ 5 ].Split( '  =  ' )[ 1  ];
                  string  minite = tempArray[ 6 ].Split( '  =  ' )[ 1  ];
                  string  second = tempArray[ 7 ].Split( '  =  ' )[ 1  ];

                dt  = DateTime.Parse(year +  "  -  "  + month +  "  -  "  + day +  "   "  + hour +  "  :  "  + minite +  "  :  "  +  second);
            }
              catch   (WebException)
            {
                  return  DateTime.Parse( "  2011-1-1  "  );
            }
              catch   (Exception)
            {
                  return  DateTime.Parse( "  2011-1-1  "  );
            }
              finally  
            {
                  if  (wrp !=  null  )
                    wrp.Close();
                  if  (wrt !=  null  )
                    wrt.Abort();
            }
              return   dt;

        }
    } 


获取网络时间,返回一个DateTime对象,然后传给设置系统时间的方法,修改系统时间。

同步系统时间:

 using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  using   System.IO;
  using   System.Net;
  using   System.Net.Sockets;
  using   System.Text.RegularExpressions;
  using   System.Runtime.InteropServices;
  using   System.Runtime;    


      ///   <summary> 
     ///   更新系统时间
      ///   </summary> 
     public   class   UpdateTime
    {
          //  设置系统时间的API函数 
        [DllImport( "  kernel32.dll  "  )]
          private   static   extern   bool  SetLocalTime( ref   SYSTEMTIME time);

        [StructLayout(LayoutKind.Sequential)]
          private   struct   SYSTEMTIME
        {
              public   short   year;
              public   short   month;
              public   short   dayOfWeek;
              public   short   day;
              public   short   hour;
              public   short   minute;
              public   short   second;
              public   short   milliseconds;
        }

          ///   <summary> 
         ///   设置系统时间
          ///   </summary> 
         ///   <param name="dt">  需要设置的时间  </param> 
         ///   <returns>  返回系统时间设置状态,true为成功,false为失败  </returns> 
         public   static   bool   SetDate(DateTime dt)
        {
            SYSTEMTIME st;

            st.year  = ( short  )dt.Year;
            st.month  = ( short  )dt.Month;
            st.dayOfWeek  = ( short  )dt.DayOfWeek;
            st.day  = ( short  )dt.Day;
            st.hour  = ( short  )dt.Hour;
            st.minute  = ( short  )dt.Minute;
            st.second  = ( short  )dt.Second;
            st.milliseconds  = ( short  )dt.Millisecond;
              bool  rt = SetLocalTime( ref   st);
              return   rt;
        }
    } 

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

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

欢迎大家光临我的CSDN博客

 

分类:  .Net

作者: Leo_wl

    

出处: http://HdhCmsTestcnblogs测试数据/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于C#同步网络时间的详细内容...

  阅读:52次