Monday, June 11, 2012

Getting time from another machine in C#.Net

This is the continuation of my previous post which is related to a tool we had to write for the production environment. There was a requirement for the tool that the DB Server, Web Server, and all should be at the same time and this post explains about getting time from another machine through C#.Net code.
When we get such a requirement, we can think about so many possibilities like exposing a WCF service, bare port communication via sockets, etc…But the easier way (may be not fully dependable) was issuing a net time command from C# and read the console using Process class.
When we issue the net time command in the normal command window the output will look as follows. We had to retrieve the DateTime object from this raw text.
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\joyg>net time \\[machine name]
Current time at \\[machine name] is 5/25/2012 8:23:54 PM

The command completed successfully.

C:\Users\joyg>

Had to use really bad programming practice of splitting the string with “\r\n” and again split using the word “is”. What will happen to the word “is” when the user runs the tool in a different locale? How can I trust the date-time string if the target machine is in a different time zone? God knows…Anyway I am sharing the code with you. Use it at your risk.

private DateTime ReadRemoteTime(string machineName)
{
    string cmd= "/c " + @"net time \\"+machineName;
    ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd.exe", cmd)
    {
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = true
    };
    System.Diagnostics.Process proc = new System.Diagnostics.Process() {StartInfo = procStartInfo};
    proc.Start();
    proc.WaitForExit();
    string consoleOutput = proc.StandardOutput.ReadToEnd();
    //HACK:THis has a high degree of failure in non english cultures.
    string split1 = consoleOutput.Split(new string[] {"\r\n\r\n"},StringSplitOptions.RemoveEmptyEntries)[0];
    string split2 = split1.Split(new string[]{"is"},StringSplitOptions.RemoveEmptyEntries)[1];
    DateTime resultDate = DateTime.Parse(split2,CultureInfo.CurrentCulture);
    return resultDate; 
}

From my mind, I am not able to wish you Happy coding :(

No comments: