Retrieve system uptime using C#
public TimeSpan UpTime {
get {
using (var uptime = new PerformanceCounter("System", "System Up Time")) {
uptime.NextValue(); //Call this an extra time before reading its value
return TimeSpan.FromSeconds(uptime.NextValue());
}
}
}
I'm a bit late, but another simple way is to use the GetTickCount64 function, which is available starting with Windows Vista and does not overflow as GetTickCount does:
public static TimeSpan GetUpTime()
{
return TimeSpan.FromMilliseconds(GetTickCount64());
}
[DllImport("kernel32")]
extern static UInt64 GetTickCount64();
System.Environment.TickCount gets the number of milliseconds since the system was restarted.
Beware though that it is an Int32 and will overflow after 24.9 days and will become negative. See the remarks on the MDSN docs.