2013-08-31 69 views
0

對於我的應用程序需要,我想從連接LAN的服務器PC獲取當前的DateTime。谷歌搜索後,我發現MSDN Article。但它是用vb寫的。我怎麼能在c#中做到這一點?任何線索?從LAN上的遠程PC獲取DateTime

謝謝。

+0

嘗試這些轉換http://www.developerfusion.com/tools/convert/vb-to-csharp/或http://converter.telerik.com/ –

回答

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