LAN上远程PC的日期时间

时间:2013-08-31 10:30:42

标签: c#

对于我的应用程序需求,我希望从与LAN连接的服务器PC获取当前的DateTime。谷歌搜索后,我找到了MSDN Article。但它是用vb写的。我怎么能在c#中做到这一点?任何线索?

感谢。

1 个答案:

答案 0 :(得分:0)

我有另一个answer的解决方案。这对我来说非常有用。

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