Sync system time to domain controller using .NET code

佐手、 提交于 2019-12-10 04:22:54

问题


I have time based tests to run that require changing the system time multiple times during the test. I want to be able to resync the time to the domain controller time at the end of the test. I there any way to do that using .NET code (C#). I am changing the time using the p-invoke function found in:

Set time programmatically using C#

Thanks


回答1:


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();
    }
}



回答2:


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.




回答3:


You can do this using the command line tool w32tm:

w32tm /resync 

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




回答4:


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 /?


来源:https://stackoverflow.com/questions/1472225/sync-system-time-to-domain-controller-using-net-code

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