General

Get System Uptime with C#

public string GetSystemUptime()
{
	try
	{
		string systemUpTime = string.Empty;
		string query = "SELECT * FROM Win32_OperatingSystem WHERE Primary='true'";
 
		using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
		{
			foreach (ManagementObject mObject in searcher.Get())
			{
				DateTime LastBootUpTime = ManagementDateTimeConverter.ToDateTime(mObject["LastBootUpTime"].ToString());
				TimeSpan systemUpTimeSpan = TimeSpan.FromTicks((DateTime.Now - LastBootUpTime).Ticks);
 
				systemUpTime = string.Format("{0}d : {1}h : {2}m : {3}s",
						systemUpTimeSpan.Days, systemUpTimeSpan.Hours, 
						systemUpTimeSpan.Minutes, systemUpTimeSpan.Seconds);
				break;
			}
		}
 
		if (string.IsNullOrEmpty(systemUpTime))
			systemUpTime = string.Format("{0}d : {1}h : {2}m : {3}s", 0, 0, 0, 0);
 
		return systemUpTime;
	}
	catch (Exception)
	{
	}
 
	return string.Format("{0}d : {1}h : {2}m : {3}s", 0, 0, 0, 0);
}