Ashutosh said:
How can I retrieve the time of a remote system? Is there some managed
wrapper for this in .Net? I don't mind using P/Invoke also
You can use WMI:
using System.Management;
public static DateTime? GetSystemTime(string computerName) {
using (
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
string.Format(@"\\{0}\root\cimv2", computerName),
"SELECT * FROM Win32_UTCTime"
)
) {
foreach (ManagementObject time in searcher.Get()) {
int year = Convert.ToInt32(time.GetPropertyValue("Year"));
int month = Convert.ToInt32(time.GetPropertyValue("Month"));
int day = Convert.ToInt32(time.GetPropertyValue("Day"));
int hour = Convert.ToInt32(time.GetPropertyValue("Hour"));
int minute = Convert.ToInt32(time.GetPropertyValue("Minute"));
int second = Convert.ToInt32(time.GetPropertyValue("Second"));
return new DateTime(year, month, day, hour, minute, second,
DateTimeKind.Utc).ToLocalTime();
}
return null;
}
}
This code takes care to retrieve the time in UTC and convert it back to a
time local to the machine it's running on, so you don't "see" the remote
machine's time zone bias (if any), but you can also query "Win32_LocalTime"
instead and leave out the conversion if you really want the local time of
the remote machine (which should usually be the same, unless you have a
really big WAN).