Get remote PC's date time?

2020-03-07 06:27发布

问题:

Is there any class available to get a remote PC's date time in .net? In order to do it, I can use a computer name or time zone. For each case, are there different ways to get the current date time? I am using Visual Studio 2005.

回答1:

I give you a solution which uses WMI. You may or may not need the domain and security information:

try
{
    string pc = "pcname";
    //string domain = "yourdomain";
    //ConnectionOptions connection = new ConnectionOptions();
    //connection.Username = some username;
    //connection.Password = somepassword;
    //connection.Authority = "ntlmdomain:" + domain;

    string wmipath = string.Format("\\\\{0}\\root\\CIMV2", pc);
    //ManagementScope scope = new ManagementScope(
    //    string.Format("\\\\{0}\\root\\CIMV2", pc), connection);
    ManagementScope scope = new ManagementScope(wmipath);
    scope.Connect();

    ObjectQuery query = new ObjectQuery(
        "SELECT * FROM Win32_LocalTime");

    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher(scope, query);

    foreach (ManagementObject queryObj in searcher.Get())
    {
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("Win32_LocalTime instance");
        Console.WriteLine("-----------------------------------");

        Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
        Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
    }
}
catch (ManagementException err)
{
    Console.WriteLine("An error occurred while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
    Console.WriteLine("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
}


回答2:

On a Windows machine there is net time \\<remote-ip address> to get the time of a remote machine. You could use that to find the remote system time, if you want code you can wrap it up in the function to execute the shell (DOS) functions in C#.



回答3:

You can use remote WMI and the Win32_TimeZone class. You do need to have permission to execute WMI queries on that machine. Avoid hassle like this by working with UTC instead of local time.



回答4:

Since WMI code would be very slow, you can use the below code to get faster results

            string machineName = "vista-pc";

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.FileName = "net";
            proc.StartInfo.Arguments = @"time \\" + machineName;
            proc.Start();
            proc.WaitForExit();

            List<string> results = new List<string>();
            while (!proc.StandardOutput.EndOfStream)
            {
                string currentline = proc.StandardOutput.ReadLine();
                if (!string.IsNullOrEmpty(currentline))
                {
                    results.Add(currentline);
                }
            }

            string currentTime = string.Empty;
            if (results.Count > 0 && results[0].ToLower().StartsWith(@"current time at \\" +                                               machineName.ToLower() + " is "))
            {
                currentTime = results[0].Substring((@"current time at \\" + machineName.ToLower() + " is                             ").Length);

                Console.WriteLine(DateTime.Parse(currentTime));
                Console.ReadLine();
            }