关机时间,引用:https://www.coder.work/article/1589448
public static DateTime GetLastSystemShutdown()
{
string sKey = @"System\CurrentControlSet\Control\Windows";
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sKey);
string sValueName = "ShutdownTime";
byte[] val = (byte[])key.GetValue(sValueName);
long valueAsLong = BitConverter.ToInt64(val, 0);
return DateTime.FromFileTime(valueAsLong);
}
开机时间:
public static DateTime GetStartTime()
{
DateTime n = DateTime.Now;
foreach (var o in new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem").Get())
{
var obj = (ManagementObject)o;
var LastBootUpTime = obj.GetPropertyValue("LastBootUpTime").ToString();
LastBootUpTime = LastBootUpTime.Split('.').FirstOrDefault();
System.IFormatProvider format = new System.Globalization.CultureInfo("zh-CN", true);
//string strDateFormat = "yyyyMMdd";
n = DateTime.ParseExact(LastBootUpTime, "yyyyMMddHHmmss", format, DateTimeStyles.AllowWhiteSpaces);
break;
}
return n;
}