C#同步網路時間

來源:互聯網
上載者:User

客戶的機器的系統時間經常出錯,導致給他們做的軟體無法正常使用,所以後來就加了一個同步網路時間的小功能。實現起來很簡單,但是卻很使用。

這個小功能就是先擷取網路時間,然後將系統的時間修改成從網路獲得的時間。下面是具體的實現:

 

擷取網路時間: 

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://www.beijing-time.org/time.asp          /// </summary>          /// <returns>返回網路時間</returns>          public DateTime GetBeijingTime()        {                     DateTime dt;            WebRequest wrt = null;            WebResponse wrp = null;            try            {                wrt = WebRequest.Create("http://www.beijing-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修改系統時間需要管理員的許可權,下篇部落格介紹如何讓程式預設以管理員權限運行,敬請期待!

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.