Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sync system time to domain controller using .NET code

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

like image 458
helios456 Avatar asked Sep 24 '09 14:09

helios456


2 Answers

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();
    }
}
like image 157
Justin Grant Avatar answered Nov 14 '22 20:11

Justin Grant


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.

like image 41
sleske Avatar answered Nov 14 '22 22:11

sleske