Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the up time of the machine?

Tags:

.net

I would like to display the up time of the machine my code is running, how can I do that?

like image 479
Mister Dev Avatar asked Nov 05 '08 13:11

Mister Dev


4 Answers

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.
like image 128
Inisheer Avatar answered Sep 18 '22 21:09

Inisheer


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)

like image 35
Mark Cidade Avatar answered Sep 19 '22 21:09

Mark Cidade


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);
like image 27
Robert Cutajar Avatar answered Sep 18 '22 21:09

Robert Cutajar


You can also use Diagnostics

using System.Diagnostics;
..........
PerformanceCounter perfc = new PerformanceCounter("System","System Up Time");
perfc.NextValue();
TimeSpan t = TimeSpan.FromSeconds(perfc.NextValue());
..........
like image 25
Bogdan Avatar answered Sep 22 '22 21:09

Bogdan