get system boot time in seconds in csharp

You can use System.Diagnostics.PerformanceCounter class to retrieve the system uptime (boot time) in seconds. Here is the code:

main.cs
using System.Diagnostics;

private static readonly DateTime StartTime = DateTime.UtcNow - TimeSpan.FromSeconds(PerformanceCounterType.PerformanceCounterTypeSystemUpTime.GetSystemUptime());

public static double GetSystemUpTimeInSeconds()
{
    using (var uptime = new PerformanceCounter("System", "System Up Time", true))
    {
        uptime.NextValue(); // Call this once to initialize the value
        return uptime.NextValue();
    }
}
441 chars
13 lines

The NextValue() method retrieves the current value of the performance counter. The PerformanceCounterType.PerformanceCounterTypeSystemUpTime.GetSystemUptime() method is used to get the initial boot time value to subtract from the current system time. The returned value is the system uptime in seconds.

gistlibby LogSnag