get system boot time in csharp

You can use the System.Diagnostics and System.Management namespaces to fetch system information including the operating system and its boot time. Here's an example code snippet that prints the system boot time as a DateTime object:

main.cs
using System;
using System.Diagnostics;
using System.Management;

namespace BootTimeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
            ManagementObjectCollection moc = mos.Get();
            DateTime lastBootUpTime = DateTime.MinValue;
            foreach (ManagementObject mo in moc)
            {
                lastBootUpTime = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
                break;
            }
            Console.WriteLine("System boot time: " + lastBootUpTime);
        }
    }
}
738 chars
23 lines

The above code works by querying the Win32_OperatingSystem WMI class for information about the primary operating system on the machine, and then reading its LastBootUpTime property which holds the time when the operating system was last booted up. Note that the LastBootUpTime field is in WMI datetime format, so we need to convert it back to a DateTime object to make it human-readable.

gistlibby LogSnag