get system boot time in milliseconds in csharp

You can use the following code to get the system boot time in milliseconds using C#:

main.cs
using System;
using System.Runtime.InteropServices;

public class BootTime
{
    [DllImport("kernel32.dll")]
    private static extern bool GetSystemTimes(out long idleTime, out long kernelTime, out long userTime);

    [DllImport("kernel32.dll")]
    private static extern uint GetLastError();

    public static DateTime GetBootTime()
    {
        long idleTime, kernelTime, userTime;
        if (GetSystemTimes(out idleTime, out kernelTime, out userTime))
        {
            return DateTime.Now.AddMilliseconds(-1 * Environment.TickCount);
        }
        else
        {
            throw new System.ComponentModel.Win32Exception((int)GetLastError());
        }
    }

    public static double GetBootTimeMilliseconds()
    {
        return (DateTime.Now - GetBootTime()).TotalMilliseconds;
    }
}
808 chars
30 lines

You can call the GetBootTimeMilliseconds() method to get the system boot time in milliseconds.

gistlibby LogSnag