Get remote PC's date time?

后端 未结 4 1349
误落风尘
误落风尘 2021-01-15 00:12

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 g

4条回答
  •  清歌不尽
    2021-01-15 00:39

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

提交回复
热议问题