Sync system time to domain controller using .NET code

£可爱£侵袭症+ 提交于 2019-12-05 06:29:58

One easy way would be to launch a process and run the NET TIME command (copied from http://blogs.msdn.com/sanket/archive/2006/11/02/synchronizing-machine-time-with-domain-controller.aspx)

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        Process netTime = new Process();

        netTime.StartInfo.FileName   = "NET.exe";
        netTime.StartInfo.Arguments = "TIME /domain:mydomainname /SET /Y";
        netTime.Start();
    }
}

As an addition to the other answers:

You should seriously consider making the notion of "current time" somehow injectable into your system. Directly reading from the system clock is very problematic (even when running the app), precisely because it is global state.

You can do this using the command line tool w32tm:

w32tm /resync 

This is neither C# nor .NET, but it hopefully fits your requirements.

The easiest way would be to use System.Diagnostics.Process to run a net time command with the appropriate parameters to sync back to your DC.

Run this from a command prompt to see what I'm talking about:

net time /?
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!