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

Would you like to get the most interesting content about C# every Monday?
Sign up to C# Digest and stay up to date!