tags:

views:

968

answers:

6

Is there a simple way to get a system's uptime using C#?

+3  A: 

Simple, no but it can be done:

    static DateTime getLastBootTime(ManagementObject mObject)
    {
        PropertyData pd = mObject.Properties["LastBootUpTime"];
        string name = pd.Name.ToString();
        DateTime lastBoot = parseCmiDateTime(pd.Value.ToString());
        return lastBoot;
    }

    static ManagementObject getServerOSObject(string serverName)
    {
        ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("Select * From Win32_OperatingSystem");
        mSearcher.Scope = new ManagementScope(String.Format(@"\\{0}\root\cimv2", serverName));
        ManagementObjectCollection mObjects = mSearcher.Get();
        if (mObjects.Count != 1) throw new Exception(String.Format("Expected 1 object, returned {0}.", mObjects.Count));
        foreach (ManagementObject m in mObjects)
        {
            //No indexing on collection
            return m;
        }
        throw new Exception("Something went wrong!");
    }
C. Ross
+5  A: 

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.

adrianbanks
To be pedantic, convert that property to milliseconds with TimeSpan.TicksPerMillisecond (http://msdn.microsoft.com/en-us/library/system.timespan.tickspermillisecond.aspx)
Michael Petrotta
Or, better yet, call TimeSpan.FromMilliseconds
SLaks
@SlLaks - am I missing something? You've got to get milliseconds from ticks before you can get a TimeSpan from milliseconds.
Michael Petrotta
@SLaks - or maybe you mean TimeSpan.FromTicks().
Michael Petrotta
Confusingly, Environment.TickCount returns a number of milliseconds, not .Net ticks (A .Net tick is 100 nanoseconds).
SLaks
http://msdn.microsoft.com/en-us/library/system.environment.tickcount.aspx
SLaks
@SLaks - Learn something new every day. Thanks.
Michael Petrotta
+8  A: 
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());
        }
    }
}
SLaks
The first call to uptime.NextValue will return 0.
SLaks
A: 

help please. all samples from this thread don't work. visual studio sayed 2 errors. public TimeSpan UpTime {

and

using (var uptime = new PerformanceCounter("System", "System Up Time")) {

sorry for my bad english because i'm russian, but russian coders don't coded this sample :(

I was able to get the code from the selected answer to work. Make sure to include "using System.Diagnostics;" at the very top of your code.
ProgrammingPope
+2  A: 

The simplest and proper way to do this is

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