Jakub Chodounsk√Ĺ

Retrieve Computer Uptime in C#

Here is a simple code snippet for retrieving computer uptime in C#. You have to add System.Management.dll to your project references.

public static TimeSpan GetUptime()
{
     var mo = new ManagementObject(@"\\.\root\cimv2:Win32_OperatingSystem=@");
     var lastBootUp = ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString());
     return DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime();
}