How to get machine uptime?

I would like to show the runtime of the computer on which my code is running, how can I do this?

+4
Nov 05 '08 at 13:09
source share
9 answers

I suggest you use the command line: net statistics workstation and analyze the output. Machine hours after "Statistics s".

-one
Nov 05 '08 at 13:10
source share

Try this link. It uses the System.Environment.TickCount property

Gets the number of milliseconds that have passed 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 since TickCount is Int32.
+10
Nov 05 '08 at 13:17
source share
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 http://bytes.com/forum/thread502885.html )

+5
Nov 05 '08 at 15:25
source share

You can also use Diagnostics.

 using System.Diagnostics; .......... PerformanceCounter perfc = new PerformanceCounter("System","System Up Time"); perfc.NextValue(); TimeSpan t = TimeSpan.FromSeconds(perfc.NextValue()); .......... 
+2
Nov 05 '08 at 13:23
source share

The easiest and most correct way to do this:

 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(); } 
+1
Aug 02 '10 at 12:17
source share

Curious that not one of them has reviewed the Stopwatch yet?

Accurate and larger than System.Environment.TickCount , not related to horrible OS performances, WMI or native calls, and very simple:

 var ticks = Stopwatch.GetTimestamp(); var uptime = ((double)ticks) / Stopwatch.Frequency; var uptimeSpan = TimeSpan.FromSeconds(uptime); 
+1
Apr 29 '14 at 14:12
source share

There are many definitions of what might mean. Assuming we are talking about an application, remote ping of a simple service may be required. Keynote provides enterprise-level solutions for the Internet, and there must be many others, many of which I could imagine.

UPDATE: if this was noted .net I assumed that we are interested in the runtime of the application. This is the application in which you want to show the operating time of the machine.

0
Nov 05 '08 at 13:11
source share

In the future, on * nix, use Uptime (1)

0
Nov 05 '08 at 13:25
source share

As a link; in the Win32 world you can use:

GetTickCount , GetTickCount64 or Performance Counters

0
Dec 30 '09 at 18:11
source share



All Articles