I would like to display the up time of the machine my code is running, how can I do that?
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.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)
Curious that none of them considered Stopwatch yet?
Precise and bigger than System.Environment.TickCount
, not involving OS horrific perf counters, WMI or native calls, and well really simple:
var ticks = Stopwatch.GetTimestamp();
var uptime = ((double)ticks) / Stopwatch.Frequency;
var uptimeSpan = TimeSpan.FromSeconds(uptime);
You can also use Diagnostics
using System.Diagnostics;
..........
PerformanceCounter perfc = new PerformanceCounter("System","System Up Time");
perfc.NextValue();
TimeSpan t = TimeSpan.FromSeconds(perfc.NextValue());
..........
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With