How to know when was Windows started or shutdown?

前端 未结 7 706
粉色の甜心
粉色の甜心 2020-12-10 05:12

I need to develop a program in C# find out when was Windows started or shutdown.

Is there a log file that I can read to know Windows start and shutdown times? Or do

7条回答
  •  旧时难觅i
    2020-12-10 05:27

    As Reed pointed out you could access the Event Logs and see when they were created. AFAIK there are no specific event entries for system startup/shutdown, but you could look for services that are usually started/stopped with Windows. Though using this approach means it won't be 100% accurate, say if it crashes or it's manually started/stopped/restarted. One event I consider is the most accurate is EventLog service start/stop event.

    if (EventLog.Exists("System"))
    {
        var log = new EventLog("System", Environment.MachineName, "EventLog");
    
        var entries = new EventLogEntry[log.Entries.Count];
        log.Entries.CopyTo(entries, 0);
    
        var startupTimes = entries.Where(x => x.InstanceId == 2147489653).Select(x => x.TimeGenerated);
        var shutdownTimes = entries.Where(x => x.InstanceId == 2147489654).Select(x => x.TimeGenerated);
    }
    

    Edit

    Turns out there was a shutdown event. You can replace the Linq to get it:

    var shutdownEvents = entries.Where(x => x.InstanceId == 2147484722);
    

提交回复
热议问题