To get the system uptime in C# and VB.NET you can use the following snippet.

Sample C#

private static String GetSystemUpTimeInfo()
{
	try
	{
		var time = GetSystemUpTime();
		var upTime = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", time.Hours, time.Minutes, time.Seconds, time.Milliseconds);
		return String.Format("{0}", upTime);
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return String.Empty;
	}
}

private static TimeSpan GetSystemUpTime()
{
	try
	{
		using (var uptime = new PerformanceCounter("System", "System Up Time"))
		{
			uptime.NextValue();
			return TimeSpan.FromSeconds(uptime.NextValue());
		}
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return new TimeSpan(0, 0, 0, 0);
	}
}

Sample VB.NET

Private Shared Function GetSystemUpTimeInfo() As String
        Try 
            Dim time As var = GetSystemUpTime
            Dim upTime As var = String.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", time.Hours, time.Minutes, time.Seconds, time.Milliseconds)
            Return String.Format("{0}", upTime)
        Catch ex As Exception
            'handle the exception your way
            Return String.Empty
        End Try
    End Function
    
    Private Shared Function GetSystemUpTime() As TimeSpan
        Try 
            Dim uptime As var = New PerformanceCounter("System", "System Up Time")
            uptime.NextValue
            Return TimeSpan.FromSeconds(uptime.NextValue)
        Catch ex As Exception
            'handle the exception your way
            Return New TimeSpan(0, 0, 0, 0)
        End Try
    End Function

One thought on “How to get the system uptime in C# and VB.NET”

Leave a Reply