Page 1 of 1

How to determine system uptime without overflow issues in C#

Posted: Thu Dec 31, 2009 9:36 am
by Cyclops
Environment.TickCount returns a 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started. But this value can overflow for systems that stay up for days at a time.

To avoid this overflow problem, you can query the "System Up Time" performance counter:

Code: Select all

public TimeSpan SystemUpTime()
{
  PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");

  // You've got to call this twice. First time it returns 0 and the second time it returns the real info.
  upTime.NextValue();
   
  return TimeSpan.FromSeconds(upTime.NextValue());
}