I want to know on when was the last time the system was started.
Environment.TickCount will work but it is breaking after 48-49 days because of the limitation of int
You're correct that Environment.TickCount
will overflow after approximately 25 days, because the return value is a 32-bit integer.
But there's a better way than trying to compare the TickCount
if you want to determine when the system was last started. What you're looking for is called the system up-time. There are a couple of different ways that you can retrieve this.
The easiest way is to use the PerformanceCounter class (in the System.Diagnostics
namespace), which lets you query a particular system performance counter. Try the following code:
TimeSpan upTime;
using (var pc = new PerformanceCounter("System", "System Up Time"))
{
pc.NextValue(); //The first call returns 0, so call this twice
upTime = TimeSpan.FromSeconds(pc.NextValue());
}
Console.WriteLine(upTime.ToString());
Alternatively, you can do this through WMI. But it looks like stian.net's answer has that covered.
Note, finally, that the performance counter's name must be localized if you need to support international versions of Windows, so the correct solution must look up the localized strings for "System" and "System Up Time" using PdhLookupPerfNameByIndex, or you must ensure you are using the PdhAddEnglishCounter under the hood, which is only supported in Vista or higher. More about this here.