I would like to display the up time of the machine my code is running, how can I do that?
I suggest you to use the command line : net statistics workstation and parse the output. The time that machine is running is after "Statistics since ".
There's many definitions of what up could mean. Assuming we are talking about an application, then a remote ping of a simple service might suffice. Keynote provide enterprise level solutions for the web and there must be many others out, many free i would imagine.
UPDATE: given this was tagged .net I assumed we are interested in the uptime of an application. Is it an application within which you want to show uptime of the machine.
Try this link. It uses the System.Environment.TickCount property
Gets the number of milliseconds elapsed since the system started. - MSDN
http://msdn.microsoft.com/en-us/library/system.environment.tickcount(VS.80).aspx
Note: this method will work for 25 days because TickCount is an Int32.You can also use Diagnostics
using System.Diagnostics;
..........
PerformanceCounter perfc = new PerformanceCounter("System","System Up Time");
perfc.NextValue();
TimeSpan t = TimeSpan.FromSeconds(perfc.NextValue());
..........
using System.Management;
using System.Linq;
TimeSpan GetUptime()
{ var query = new SelectQuery("SELECT LastBootUpTime
FROM Win32_OperatingSystem
WHERE Primary='true'");
var mos = new ManagementObjectSearcher(query);
var str = mos.Get().First().Properties["LastBootUpTime"].Value.ToString();
return DateTime.Now - ManagementDateTimeConverter.ToDateTime(str);
}
(Based on code from http://bytes.com/forum/thread502885.html)
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();
}