使用.NET获取上次Windows关闭事件的日期时间

Sam*_*eet 7 .net c# time wmi shutdown

有没有办法找出系统上次关机的时间?

我知道有一种方法可以使用WMIWin32_OperatingSystem命名空间中使用LastBootUpTime属性找出上次启动时间.

是否有类似的发现最后关机时间?

谢谢.

JDu*_*ley 8

假设Windows顺利关闭.它将其存储在注册表中:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ShutdownTime
Run Code Online (Sandbox Code Playgroud)

它存储为字节数组,但是是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;
    }
Run Code Online (Sandbox Code Playgroud)


Abe*_*bel 8

(这里的一切都是100%由JDunkerley先前的答案提供)

解决方案在上面,但是从byte数组到达的DateTime方法可以使用更少的语句来实现BitConverter.以下六行代码执行相同的操作并DateTime从注册表中提供正确的:

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);
}
Run Code Online (Sandbox Code Playgroud)