`
ihuashao
  • 浏览: 4749367 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

Get Windows Uptime using C# and WMI

阅读更多

Sometime ago I use to compare my OS uptime with some friends; it was like an Uptime Competition (We had a lot of free time ;-)). I don't know why but today I remembered it and I thought about if I could obtain my OS Uptime using C#. About one year ago or so I worked a bit with WMI when I was coding against the Windows Media Server API, and since then I think that WMI is a good way to obtain information about our system.

I've checked the WMI reference at MSND and I got a WMI class that has the last time boot up date. The class that hosts this date is Win32_OperatingSystem among other data; such Windows install date and other interesting things. Once we have that the only thing we can do is... to Code !!

The method shown below obtains the last boot up time from the property LastBootUpTime of the Win32_OperatingSystem class, so I created ManagementClass object to get the instances of the WMI class. Then I looped thought it elements to obtain the date, it's easy.

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> 1 /// 2 /// Obtains the OS uptime 3 /// 4 /// TimeSpan object that contains the uptime 5 public TimeSpan GetUptime() 6 { 7 //timespan object to store the result value 8 TimeSpan uptimeTs = new TimeSpan(); 9 10 //management objects to interact with WMI 11 ManagementClass management = new ManagementClass("Win32_OperatingSystem"); 12 ManagementObjectCollection mngInstance = management.GetInstances(); 13 14 //loop throught the mngInstance 15 foreach (ManagementObject mngObject in mngInstance) 16 { 17 //get the LastBootUpTime date parsed 18 DateTime lastBootUp = ParseCIMDateTime(mngObject["LastBootUpTime"].ToString()); 19 20 //check it value is not DateTime.MinValue 21 if (lastBootUp != DateTime.MinValue) 22 { 23 //get the diff between dates 24 uptimeTs = DateTime.Now - lastBootUp; 25 } 26 } 27 28 //return the uptime TimeSpan 29 return uptimeTs; 30 }


The DateTime format that WMI works with is the CIM_DATETIME. The dates are represented as strings with a specific format. This format is covered in depth at WMI reference at MSDN. But the date format isn't a problem, it's a human readable format. The string 20070112204559.115081+060 represents 12/01/2007 20:45:59,115, so I created a method to parse CIM dates to .Net DateTime objects.

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> 1 /// 2 /// Parses a CIM_DateTime string 3 /// 4 /// 5 /// The CIM_DateTime format is represented by the following string: 6 /// yyyy MM dd hh mm ss.mmm mmm UTC 7 /// 2007 01 12 20 45 59.115 081+060 8 /// 9 /// Input CIM_DateTime string 10 /// DatTime object that represents the CIM_DateTIme input string 11 private static DateTime ParseCIMDateTime(string wmiDate) 12 { 13 //datetime object to store the return value 14 DateTime date = DateTime.MinValue; 15 16 //check date integrity 17 if (wmiDate != null && wmiDate.IndexOf('.') != -1) 18 { 19 //obtain the date with miliseconds 20 string tempDate = wmiDate.Substring(0, wmiDate.IndexOf('.') + 4); 21 22 //check the lenght 23 if (tempDate.Length == 18) 24 { 25 //extract each date component 26 int year = Convert.ToInt32(tempDate.Substring(0, 4)); 27 int month = Convert.ToInt32(tempDate.Substring(4, 2)); 28 int day = Convert.ToInt32(tempDate.Substring(6, 2)); 29 int hour = Convert.ToInt32(tempDate.Substring(8, 2)); 30 int minute = Convert.ToInt32(tempDate.Substring(10, 2)); 31 int second = Convert.ToInt32(tempDate.Substring(12, 2)); 32 int milisecond = Convert.ToInt32(tempDate.Substring(15, 3)); 33 34 //compose the new datetime object 35 date = new DateTime(year, month, day, hour, minute, second, milisecond); 36 } 37 } 38 39 //return datetime 40 return date; 41 }


This is all the logic that we need to obtain our OS uptime. I wrote a small console application that outputs the OS uptime in the format:

"Uptime: 7 days, 2 hours, 2 minutes, 7 seconds and 317 milliseconds"

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> 1 /// <summary> 2 /// Console entry point 3 /// </summary> 4 private static void Main() 5 { 6 //create an instace of the UpTime class 7 Uptime uptime = new Uptime(); 8 9 //obtain the TimeSpan that represents the uptime 10 TimeSpan ts = uptime.GetUptime(); 11 12 //write the uptime to the output 13 Console.WriteLine(String.Format("Uptime: {0} days, {1} hours, {2} minutes, {3} seconds and {4} miliseconds", 14 ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds)); 15 }





WMI Reference at MSDN: http://msdn2.microsoft.com/en-us/library/aa394582....
Win32_OperatingSystem Class reference: http://msdn2.microsoft.com/en-us/library/aa394239....
CIM_DateTime format reference: http://msdn2.microsoft.com/en-us/library/aa387237....

That's all folks!! I hope you like it

分享到:
评论

相关推荐

    C#开机时长

    首先,我们需要了解Windows操作系统中用于存储系统信息的API,即Windows Management Instrumentation(WMI)。WMI是一个基于Common Information Model (CIM) 的接口,允许开发者访问和管理本地或远程系统的硬件、...

    数据中心Uptime设计认证的难点及分析.pdf

    数据中心 Uptime 设计认证的难点及分析 数据中心 Uptime 设计认证是当前数据中心行业中的一项重要认证标准。随着国内运营商对数据中心进行 Uptime 设计认证的需求越来越多,本文将简要介绍数据中心 Uptime 认证标准...

    C#获取系统开机时间

    总结一下,通过C#的`System.Management`命名空间,我们可以轻松地获取到Windows操作系统的开机时间。这涉及到`ManagementObjectSearcher`和`ManagementObject`类的使用,以及对`Win32_OperatingSystem`类中`...

    uptime指令的简单实现

    请注意,以上代码仅提供了实现`uptime`命令的基本框架,实际的`parse_uptime`、`parse_loadavg`和`get_current_time`函数需要根据`/proc`文件的具体格式进行填充。同时,为了提高可读性,这里没有展示如何处理可能的...

    UpTime系统已运行时间 v16.4.12.9

    "UpTime系统已运行时间 v16.4.12.9" 是一个关于系统运行时间监测工具的软件版本更新。这个工具的主要功能是记录和显示计算机或服务器自启动以来持续运行的时间,即"已运行时间"。在IT管理中,了解系统的运行时间对于...

    SQL Server AlwaysOn Revealed(Apress,2ed,2016)

    Get a fast start to using AlwaysOn, the SQL Server solution to high-availability and disaster recovery. This second edition is newly-updated to cover the 2016 editions of both SQL Server and Windows ...

    开源项目-MatthewJamesBoyle-uptime-gobot.zip

    开源项目-MatthewJamesBoyle-uptime-gobot.zip,Uptime gobot - track the uptime of URLs and recieve notifications when they go down. My first open source go project.

    uptime-robot.zip

    【Uptime Robot】是一款强大的网站监控工具,专为确保您的在线业务持续运行而设计。它提供了全面、实时的网站状态监控服务,相比其他常见的监控工具,如360网站卫士,Uptime Robot在功能和易用性上具有显著优势。...

    docker-uptime:Docker化的正常运行时间容器

    # Run Uptime and link MongoDB docker run -d -p 8082:8082 --name uptime --link mongodb:mongodb -i -t usman/docker-uptime # Run Uptime and link MongoDB with custom Database Password docker run -d -p ...

    mac os 10.10 uptime

    mac os 10.10 uptime

    C#简单实现SNMP的方法

    // Get the system uptime SNMP request response = conn.get("get", argv[0], argv[1], "1.3.6.1.2.1.1.3.0"); if (response[0] != 0xff) { // Extract the uptime value uptime = Convert.ToInt32(BitConverter....

    uptime-源码.rar

    "uptime" 是一个在Linux和类Unix系统中常用的命令,用于显示系统已经运行了多长时间。这个命令简单而实用,可以提供系统启动时间、当前时间、以及系统平均负载等信息。当你解压"uptime-源码.rar"后,你会得到"uptime...

    C#文件上传源代码

    根据提供的信息,我们可以总结出以下关于“C#文件上传源代码”的相关知识点: ### 1. 文件上传基础知识 - **文件上传概述**:文件上传是Web应用中的常见功能之一,通常用于用户向服务器提交文件(如图片、文档等)...

    linux中uptime命令的用法详细解析

    在Linux操作系统中,`uptime`命令是一个非常实用的工具,用于获取系统运行状态的基本信息,包括主机运行时间、登录用户数量以及系统负载等关键数据。本文将深入解析`uptime`命令的用法及其显示结果的含义。 首先,...

    Uptime Tier Standard Topology

    《Uptime Tier Standard Topology》是Uptime Institute发布的一个标准,用于评估和比较数据中心站点基础设施的设计和性能。这个标准基于四个级别的冗余容量组件和分配路径来区分不同的系统架构,以确保不同需求的...

    UpTime系统已运行时间工具

    软件简介: 在Win7/2008以后,使用Task Manager可以查看系统已运行...1. 增加UpTime及LastBoot的自订输出变数。 2. File选单增加重新启动程式功能,并只允许单一程式执行。 Snapshot: http://i.imgur.com/po54nit.png

Global site tag (gtag.js) - Google Analytics