Search code examples
c#.nettimewmishutdown

Get the date-time of last windows shutdown event using .NET


Is there a way to find out when the system was last shutdown?

I know there's a way to find out last boot up time using the LastBootUpTime property in Win32_OperatingSystem namespace using WMI.

Is there anything similar to find out last shutdown time?

Thanks.


Solution

  • (everything here is 100% courtesy of JDunkerley's earlier answer)

    The solution is above, but the approach of going from a byte array to DateTime can be achieved with fewer statements using the BitConverter.The following six lines of code do the same and give the correct DateTime from the registry:

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