Subscribe to Blog.Parse(typeof(PsychoCoder), Richard McCutchen);        RSS Feed
-----

Use WMI & C# to get system's up-time

Icon Leave Comment
Recently I needed the ability to get the systems up-time, no matter what system the application may be currently running on. After many hours on Bing I came to the conclusion that there are literally hundreds (if not thousands) of ways to accomplish this. I chose using Windows Management Instrumentation (WMI) as I'm very familiar with the way WMI works (As this application utilizes WMI for a lot of it's functionality).

Now you need to know, the format of DateTime and WMI can handle is in CIM_DATETIME (Common Information Model) so it would have to be parsed to bring it back to a normal, everyday DateTime value. This happens to be your luck day then as we do have a method (we wrote, it's not built into the Framework) that accepts a datetime in the CIM format and returns a normal DataTime.

That method looks like this

/// <summary>
/// method used to parse the datetime returned from a WMI call. The date format
/// that WMI works well with is CIM_DATETIME. The date is stored as a humany readable
/// format, such as 20100101161959.115081+060 (This represents 01/01/2010 16:19:59) This
/// method converts CIM_DATETIME values into .Net readable DateTime object
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
private DateTime ParseCIM_DATETIME(string date)
{
	//datetime object to store the return value
	DateTime parsed = DateTime.MinValue;

	//check date integrity
	if (date != null && date.IndexOf('.') != -1)
	{
		//obtain the date with miliseconds
		string newDate = date.Substring(0, date.IndexOf('.') + 4);

		//check the lenght
		if (newDate.Length == 18)
		{
			//extract each date component
			int y = Convert.ToInt32(newDate.Substring(0, 4));
			int m = Convert.ToInt32(newDate.Substring(4, 2));
			int d = Convert.ToInt32(newDate.Substring(6, 2));
			int h = Convert.ToInt32(newDate.Substring(8, 2));
			int mm = Convert.ToInt32(newDate.Substring(10, 2));
			int s = Convert.ToInt32(newDate.Substring(12, 2));
			int ms = Convert.ToInt32(newDate.Substring(15, 3));

			//compose the new datetime object
			parsed = new DateTime(y, m, d, h, mm, s, ms);
		}
	}

	//return datetime
	return parsed;
}



Now the parsing functionality if completed we can now focus on the task at hand, finding out how long a computer has been running (it's up-time). WMI gives us access to lots of classes, the one we need for this is the Win32_Operating System Class, this class gives us access to LastBootUpTime (A DateTime type) that holds the date/time the computer was last rebooted.

Given [b]LastBootUpTime[/url] we can subtract that value from [b]DateTime.Now[/url] (which is set to a Timespan type) and find out how long the system has been up. With no further ado let's take a look at the code for retrieving the systems up-time

/// <summary>
/// method to get the current systems up-time, returned in a Timespan value
/// </summary>
/// <returns></returns>
public TimeSpan GetSystemUptime()
{
	//timespan object to store the result value
	TimeSpan up = new TimeSpan();

	//management objects to interact with WMI
	ManagementClass m = new ManagementClass("Win32_OperatingSystem");

	//loop throught the WMI instances
	foreach (ManagementObject instance in m.GetInstances())
	{
		//get the LastBootUpTime date parsed (comes in CIM_DATETIME format)
		DateTime last = ParseCIMDateTimeFormat(instance["LastBootUpTime"].ToString());

		//check it value is not DateTime.MinValue
		if (last != DateTime.MinValue)
			//get the diff between dates
			up = DateTime.Now - last;
	}

	//return the uptime TimeSpan
	return up;
}



Ok, so we have the current up-time in a Timespan type so we can now access that something like this

Timespan span = GetSystemUptime();

label1.Text = string.Format("Up-Time:  {0} Days, {1} Hours, {2} Minutes, {3} Seconds", span.Days, span.Hours, span.Minutes, span.Seconds);



Well I hope you found this interesting and informative. Thanks for reading & happy coding! :)

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

May 2020

S M T W T F S
     12
3456789
10111213141516
17181920212223
2425262728 29 30
31      

Recent Entries

Search My Blog

2 user(s) viewing

2 Guests
0 member(s)
0 anonymous member(s)