saville

博客园 首页 新随笔 联系 订阅 管理

WMI 是微软操作系统的一个内置的组件,通过使用WMI我们可以获取服务器硬件信息、收集服务器性能数据、操作Windows服务,甚至可以远程关机或是重启服务器。

一、在C#编程中使用WMI

要想在C#程序中使用WMI,必须添加System.Management.dll的引用,并使用System.Management命名空间。该命名空间提供对一组符合WMI基础结构的系统、设备和应用程序的管理信息和管理事件的访问。这里介绍一下常用的几个类:

ManagementScope用以连接WMI命名空间。

ManagementBaseObject包含管理对象的基本元素。

ManagementObject表示WMI实例。

ManagementObjectCollection表示通过WMI检索到的管理对象的集合。

ManagementObjectSearcher表示基于指定的查询检索管理对象的集合。该类也是用于检索管理信息的较为常用的入口点之一。

本人在写代码时将自己常用的一些关于WMI的基本操作进行了简单的包装。

1.ManagementScope

 1     public ManagementScope GetManagementScope()
 2     {
 3         if (_managementScope == null)
 4         {
 5             if (Environment.MachineName.ToLower() == ServerName.ToLower())
 6             {
 7                 _managementScope = new ManagementScope("\\\\" + ServerIP + "\\root\\cimv2");
 8             }
 9             else if (UserName != null && UserName.Length > 0)
10             {
11                 ConnectionOptions connectionOptions = new ConnectionOptions();
12                 connectionOptions.Username = UserName;
13                 connectionOptions.Password = Password;
14                 _managementScope = new ManagementScope("\\\\" + ServerIP + "\\root\\cimv2", connectionOptions);
15             }
16             else
17             {
18                 throw new ManagementException();
19             }
20         }
21         return _managementScope;
22     }

2.ManagementObjectSearcher

1     private ManagementObjectSearcher GetManagementObjectSearcher(string wql)
2     {
3         return new ManagementObjectSearcher(GetManagementScope(), new SelectQuery(wql));
4     }

3.得到ManagementBaseObject集合

 1     public List<ManagementBaseObject> GetManagementObjects(string wql)
 2     {
 3         List<ManagementBaseObject> managementObjects = new List<ManagementBaseObject>();
 4         ManagementObjectCollection collection = GetManagementObjectCollection(wql);
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             managementObjects.Add(managementObject);
 8         }
 9         return managementObjects;
10     }

4.获取系统信息

1     public object GetSystemInfo(ManagementBaseObject managementObject, string type)
2     {
3         return managementObject[type];
4     }
5     public object GetSystemInfo(string wql, string type)
6     {
7         return GetSystemInfo(GetManagementObjects(wql)[0], type);
8     }

有了这些基本操作作为基础,我们就来看一下如何方便的获取CPU、内存、硬盘等基本信息。

二、CPU

1.CPU型号

1     public string Model()
2     {
3         return GetSystemInfo("SELECT * FROM Win32_Processor", "Name").ToString().Trim();
4     }

2.获取CPU个数

1     public int Number()
2     {
3         return GetManagementObjects("SELECT * FROM Win32_Processor").Count;
4     }

3.CPU使用率

 1     public int AverageLoadPercentage()
 2     {
 3         int loadPercentage = 0;
 4         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_Processor");
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             object load = GetSystemInfo(managementObject, "LoadPercentage");
 8             if (load == null)
 9             {
10                 load = 0;
11             }
12             loadPercentage += Int32.Parse(load.ToString());
13         }
14         return loadPercentage / collection.Count;
15     }

三、内存

1.总内存数

 1     public string TotalSize()
 2     {
 3         float size = 0;
 4         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_OperatingSystem");
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             size += long.Parse(GetSystemInfo(managementObject, "TotalVisibleMemorySize").ToString());
 8         }
 9         return (size / 1024).ToString("0.00") + "MB";
10     }

2.剩余内存数

 1     public string FreeSize()
 2     {
 3         float size = 0;
 4         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_OperatingSystem");
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             size += float.Parse(GetSystemInfo(managementObject, "FreePhysicalMemory").ToString());
 8         }
 9         return (size / 1024).ToString("0.00") + "MB";
10     }

四、硬盘

1.定义逻辑硬盘结构

 1     public struct LogicalDisk
 2     {
 3         private string _deviceID;
 4         private long _size;
 5         private long _freeSize;
 6 
 7         public string Size
 8         {
 9             get
10             {
11                 return ((float) _size / 1024 / 1024 / 1024).ToString("0.00") + "GB";
12             }
13         }
14 
15         public string FreeSize
16         {
17             get
18             {
19                 return ((float) _freeSize / 1024 / 1024 / 1024).ToString("0.00") + "GB";
20             }
21         }
22 
23         public LogicalDisk(string deviceID, long size, long freeSize)
24         {
25             _deviceID = deviceID;
26             _size = size;
27             _freeSize = freeSize;
28         }
29     }

2.获取逻辑硬盘信息

 1     private void GetLogicalDisk()
 2     {
 3         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_LogicalDisk WHERE DriveType = " + (int)System.IO.DriveType.Fixed);
 4 
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             long size, freeSize;
 8             object managementObjectInfo;
 9             managementObjectInfo = GetSystemInfo(managementObject, "Size");
10             if (managementObjectInfo == null)
11             {
12                 continue;
13             }
14             else
15             {
16                 size = long.Parse(GetSystemInfo(managementObject, "Size").ToString());
17             }
18             managementObjectInfo = GetSystemInfo(managementObject, "FreeSpace");
19             if (managementObjectInfo == null)
20             {
21                 freeSize = 0;
22             }
23             else
24             {
25                 freeSize = long.Parse(GetSystemInfo(managementObject, "FreeSpace").ToString());
26             }
27             string deviceID = GetSystemInfo(managementObject, "deviceid").ToString();
28             _logicalDisks.Add(new LogicalDisk(deviceID, size, freeSize));
29         }
30     }

五、Windows服务

1.两个辅助方法

1     private ManagementObject GetServiceObject()
2     {
3         return GetManagementObjects("SELECT * FROM Win32_Service WHERE Name = '" + Name + "'")[0] as ManagementObject;
4     }
5 
6     private object GetManagementObjectInfo(string type)
7     {
8         return GetSystemInfo(GetServiceObject(), type);
9     }

2.服务运行状况

1     public string Status()
2     {
3         return GetManagementObjectInfo("State") as string;
4     }

3.启动服务

 1     public bool Start()
 2     {
 3         try
 4         {
 5             if (Status() == "Stopped")
 6             {
 7                 GetServiceObject().InvokeMethod("StartService", null);
 8                 while (Status() == "Start Pending") ;
 9                 return true;
10             }
11             return false;
12         }
13         catch (Exception e)
14         {
15             throw new Exception(Name + "服务启动失败", e);
16         }
17     }

4.停止服务

 1     public bool AcceptStop()
 2     {
 3         return (bool)GetManagementObjectInfo("AcceptStop");
 4     }
 5     
 6     public bool Stop()
 7     {
 8         try
 9         {
10             if (AcceptStop())
11             {
12                 GetServiceObject().InvokeMethod("StopService", null);
13                 while (Status() == "Stop Pending") ;
14                 return true;
15             }
16             return false;
17         }
18         catch (Exception e)
19         {
20             throw new Exception(Name + "服务停止失败", e);
21         }
22     }

 

posted on 2013-06-23 20:24  saville  阅读(7325)  评论(10编辑  收藏  举报