c # to the computer network time synchronization time

Recently encountered a project that requires software to control the use of time, because the computer can not modify the network time, it needs to make networked computer network time synchronization

Internet to find a lot of solutions, as follows:

//Forproc_Win32.cs
// declaration common Win32 API function and configuration of
the using the System;
the using the System.Runtime.InteropServices;
 
namespace Farproc.Win32
{
    /// <Summary>
    ///
    /// </ Summary>
    public struct the SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort WDAY;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
 
        /// <Summary>
        /// conversion from System.DateTime.
        /// </ summary>
        /// <param name="time">System.DateTime类型的时间。</param>
        public void FromDateTime(DateTime time)
        {
            wYear = (ushort)time.Year;
            wMonth = (ushort)time.Month;
            wDayOfWeek = (ushort)time.DayOfWeek;
            wDay = (ushort)time.Day;
            wHour = (ushort)time.Hour;
            wMinute = (ushort)time.Minute;
            wSecond = (ushort)time.Second;
            wMilliseconds = (ushort)time.Millisecond;
        }
        /// <summary>
        /// 转换为System.DateTime类型。
        /// </summary>
        /// <returns></returns>
        public DateTime ToDateTime()
        {
            return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
        }
        /// <summary>
        /// 静态方法。转换为System.DateTime类型。
        /// </summary>
        /// <param name="time">SYSTEMTIME类型的时间。</param>
        /// <returns></returns>
        public static DateTime ToDateTime(SYSTEMTIME time)
        {
            return time.ToDateTime();
        }
    }
 public class Win32API
    {
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime( ref SYSTEMTIME Time );
        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SYSTEMTIME Time);
    }
}
Private void the button1_Click (Object SENDER, System.EventArgs E)
{
    // get the current system time of
    the DateTime T = the DateTime.Now;
    // at the current time plus one week
    T = t.AddDays (. 7);
    // Conversion System .DateTime to the SYSTEMTIME
    the SYSTEMTIME the SYSTEMTIME new new ST = ();
    st.FromDateTime (T);
    // set the system time Win32 API calls
    Win32API.SetLocalTime (REF ST);
    // current time
    MessageBox.Show (DateTime.Now.ToString ( ));
}

I tried many times and failed to correctly modified.

Later whim, cmd can not change the system time it?

Then use the cmd command functions successfully.

/// <summary>  
        /// 获取网络日期时间  
        /// </summary>  
        /// <returns></returns>  
        public static string GetNetDateTime()
        {
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                { if (h == "Date") { datetime = headerCollection[h]; } }
                return datetime;
            }
            catch (Exception) { return datetime; }
            finally
            {
                if (request != null)
                { request.Abort(); }
                if (response != null)
                { response.Close(); }
                if (headerCollection != null)
                { headerCollection.Clear(); }
            }
        }

// Call cmd modify the system time
        public static void SetSystemTime (the DateTime NetTime)
        {
            the System.Diagnostics.Process the System.Diagnostics.Process new new P = ();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false; // whether to use the operating system shell starts
            p.StartInfo.RedirectStandardInput = true; // accepts input from the caller's
            p.StartInfo.RedirectStandardOutput = true; // output information acquired by the calling program
            p.StartInfo.RedirectStandardError = true ; // redirect the standard error output
            p.StartInfo.CreateNoWindow = true; // do not display window
            p.Start (); // start the program

            string dtdate = netTime.ToString ( "yyyy- MM-dd"); // acquisition date
            string dttime = netTime.ToString ( "HH: mm: ss"); // get time
            string dos1 = "date" + dtdate ; // command. 1
            String DOS 2 = "Time" + dttime; // Command 2
            p.StandardInput.WriteLine (DOS1 + "&" + DOS 2 + "& Exit");
            p.StandardInput.AutoFlush to true =;
            String = p.StandardOutput.ReadToEnd the Output ();
            p.WaitForExit (); // waiting for the program to exit the process finished
            p.Close ();
        }

Guess you like

Origin www.cnblogs.com/jianliu/p/11206971.html