We help IT Professionals succeed at work.

How to sync client computer time with a server computer time using C#

sepknow
sepknow asked
on
How to sync client computer time with a server computer time using C#?
(besides using "use net time \\servername /set /y").
Comment
Watch Question

In general this is a very bad thing to do.  Clients using C# will be running on a Windows platform and should have a local, correct time.  This is required for domains to function correctly and the Windows Time Service provides this function.  See http://blogs.bdnet.co.uk/steve/archive/2008/01/06/The-Windows-Time-Service.aspx.

Also, you normally need local administrator rights to change the system time.

Nevertheless, if you have the security privileges you can do this using WMI.

See the following for WMI and scripting references:
http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov07/hey1116.mspx
http://msdn2.microsoft.com/en-us/library/aa393289(VS.85).aspx

To do this in C#, you need to use the System.Management namespace which exposes WMI functionality.  You will need to use the Invoke method to run the SetDateTime method of the Win32_OperatingSystem object.

See http://msdn.microsoft.com/msdnmag/issues/02/05/WMIMan/ for an intro to WMI in .NET.  and http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.wmi&tid=5388448d-2944-4138-9796-c91350b6510a&p=1 for an example.

You might find that an easier option is to use Platform Invoke with the SetSystemTime Win32 function which is referenced here:

http://msdn2.microsoft.com/en-us/library/ms724942(VS.85).aspx

Here's an old example for Visual Basic (not .NET): http://support.microsoft.com/kb/154009.

Author

Commented:
Quite a bit to digest.
Let me go through and come back to you later.
Thanks.
You're welcome.  If you get stuck, feel free to ask.  I'll be away from my desk later, but there are other experts too...
Thanks for the points :)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.