【发布时间】:2009-10-27 16:12:32
【问题描述】:
有没有办法查出系统上次关闭的时间?
我知道有一种方法可以使用 Win32_OperatingSystem 命名空间中的 LastBootUpTime 属性(使用 WMI)找出上次启动时间。
有什么类似的可以查到上次关机时间吗?
谢谢。
【问题讨论】:
-
您还需要考虑您是否关心机器何时断电 - 您不会为此获得事件。
有没有办法查出系统上次关闭的时间?
我知道有一种方法可以使用 Win32_OperatingSystem 命名空间中的 LastBootUpTime 属性(使用 WMI)找出上次启动时间。
有什么类似的可以查到上次关机时间吗?
谢谢。
【问题讨论】:
(此处所有内容均 100% 由 JDunkerley's earlier answer 提供)
解决方案如上,但从byte 数组到DateTime 的方法可以通过使用BitConverter 的更少语句来实现。以下六行代码执行相同操作并给出正确的@987654325 @来自注册表:
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);
}
【讨论】:
假设 Windows 顺利关闭。它将它存储在注册表中:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ShutdownTime
它被存储为一个字节数组,但它是一个 FILETIME。
虽然可能有更好的方法,但我以前使用过,认为它有效:
public static DateTime GetLastSystemShutdown()
{
string sKey = @"System\CurrentControlSet\Control\Windows";
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sKey);
string sValueName = "ShutdownTime";
object val = key.GetValue(sValueName);
DateTime output = DateTime.MinValue;
if (val is byte[] && ((byte[])val).Length == 8)
{
byte[] bytes = (byte[])val;
System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();
int valLow = bytes[0] + 256 * (bytes[1] + 256 * (bytes[2] + 256 * bytes[3]));
int valTwo = bytes[4] + 256 * (bytes[5] + 256 * (bytes[6] + 256 * bytes[7]));
ft.dwLowDateTime = valLow;
ft.dwHighDateTime = valTwo;
DateTime UTC = DateTime.FromFileTimeUtc((((long) ft.dwHighDateTime) << 32) + ft.dwLowDateTime);
TimeZoneInfo lcl = TimeZoneInfo.Local;
TimeZoneInfo utc = TimeZoneInfo.Utc;
output = TimeZoneInfo.ConvertTime(UTC, utc, lcl);
}
return output;
}
【讨论】:
DateTime,希望你不介意,但如果没有我就做不到你的答案:)
使用这段代码可以找到上次重启时间
static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromMilliseconds(System.Environment.TickCount);
Console.WriteLine( DateTime.Now.Subtract(t));
}
【讨论】: