WMI 是微软操作系统的一个内置的组件,通过使用WMI我们可以获取服务器硬件信息、收集服务器性能数据、操作Windows服务,甚至可以远程关机或是重启服务器。
一、在C#编程中使用WMI
要想在C#程序中使用WMI,必须添加System.Management.dll的引用,并使用System.Management命名空间。该命名空间提供对一组符合WMI基础结构的系统、设备和应用程序的管理信息和管理事件的访问。这里介绍一下常用的几个类:
ManagementScope用以连接WMI命名空间。
ManagementBaseObject包含管理对象的基本元素。
ManagementObject表示WMI实例。
ManagementObjectCollection表示通过WMI检索到的管理对象的集合。
ManagementObjectSearcher表示基于指定的查询检索管理对象的集合。该类也是用于检索管理信息的较为常用的入口点之一。
本人在写代码时将自己常用的一些关于WMI的基本操作进行了简单的包装。
1.ManagementScope
public ManagementScope GetManagementScope()
{
if (_managementScope == null)
{
if (Environment.MachineName.ToLower() == ServerName.ToLower())
{
_managementScope = new ManagementScope("\\\\" + ServerIP + "\\root\\cimv2");
}
else if (UserName != null && UserName.Length > )
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = UserName;
connectionOptions.Password = Password;
_managementScope = new ManagementScope("\\\\" + ServerIP + "\\root\\cimv2", connectionOptions);
}
else
{
throw new ManagementException();
}
}
return _managementScope;
}
2.ManagementObjectSearcher
private ManagementObjectSearcher GetManagementObjectSearcher(string wql)
{
return new ManagementObjectSearcher(GetManagementScope(), new SelectQuery(wql));
}
3.得到ManagementBaseObject集合
public List<ManagementBaseObject> GetManagementObjects(string wql)
{
List<ManagementBaseObject> managementObjects = new List<ManagementBaseObject>();
ManagementObjectCollection collection = GetManagementObjectCollection(wql);
foreach (ManagementObject managementObject in collection)
{
managementObjects.Add(managementObject);
}
return managementObjects;
}
4.获取系统信息
public object GetSystemInfo(ManagementBaseObject managementObject, string type)
{
return managementObject[type];
}
public object GetSystemInfo(string wql, string type)
{
return GetSystemInfo(GetManagementObjects(wql)[], type);
}
有了这些基本操作作为基础,我们就来看一下如何方便的获取CPU、内存、硬盘等基本信息。
二、CPU
1.CPU型号
public string Model()
{
return GetSystemInfo("SELECT * FROM Win32_Processor", "Name").ToString().Trim();
}
2.获取CPU个数
public int Number()
{
return GetManagementObjects("SELECT * FROM Win32_Processor").Count;
}
3.CPU使用率
public int AverageLoadPercentage()
{
int loadPercentage = ;
List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_Processor");
foreach (ManagementObject managementObject in collection)
{
object load = GetSystemInfo(managementObject, "LoadPercentage");
if (load == null)
{
load = ;
}
loadPercentage += Int32.Parse(load.ToString());
}
return loadPercentage / collection.Count;
}
三、内存
1.总内存数
public string TotalSize()
{
float size = ;
List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_OperatingSystem");
foreach (ManagementObject managementObject in collection)
{
size += long.Parse(GetSystemInfo(managementObject, "TotalVisibleMemorySize").ToString());
}
return (size / ).ToString("0.00") + "MB";
}
2.剩余内存数
public string FreeSize()
{
float size = ;
List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_OperatingSystem");
foreach (ManagementObject managementObject in collection)
{
size += float.Parse(GetSystemInfo(managementObject, "FreePhysicalMemory").ToString());
}
return (size / ).ToString("0.00") + "MB";
}
四、硬盘
1.定义逻辑硬盘结构
public struct LogicalDisk
{
private string _deviceID;
private long _size;
private long _freeSize; public string Size
{
get
{
return ((float) _size / / / ).ToString("0.00") + "GB";
}
} public string FreeSize
{
get
{
return ((float) _freeSize / / / ).ToString("0.00") + "GB";
}
} public LogicalDisk(string deviceID, long size, long freeSize)
{
_deviceID = deviceID;
_size = size;
_freeSize = freeSize;
}
}
2.获取逻辑硬盘信息
private void GetLogicalDisk()
{
List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_LogicalDisk WHERE DriveType = " + (int)System.IO.DriveType.Fixed); foreach (ManagementObject managementObject in collection)
{
long size, freeSize;
object managementObjectInfo;
managementObjectInfo = GetSystemInfo(managementObject, "Size");
if (managementObjectInfo == null)
{
continue;
}
else
{
size = long.Parse(GetSystemInfo(managementObject, "Size").ToString());
}
managementObjectInfo = GetSystemInfo(managementObject, "FreeSpace");
if (managementObjectInfo == null)
{
freeSize = ;
}
else
{
freeSize = long.Parse(GetSystemInfo(managementObject, "FreeSpace").ToString());
}
string deviceID = GetSystemInfo(managementObject, "deviceid").ToString();
_logicalDisks.Add(new LogicalDisk(deviceID, size, freeSize));
}
}
五、Windows服务
1.两个辅助方法
private ManagementObject GetServiceObject()
{
return GetManagementObjects("SELECT * FROM Win32_Service WHERE Name = '" + Name + "'")[] as ManagementObject;
} private object GetManagementObjectInfo(string type)
{
return GetSystemInfo(GetServiceObject(), type);
}
2.服务运行状况
public string Status()
{
return GetManagementObjectInfo("State") as string;
}
3.启动服务
public bool Start()
{
try
{
if (Status() == "Stopped")
{
GetServiceObject().InvokeMethod("StartService", null);
while (Status() == "Start Pending") ;
return true;
}
return false;
}
catch (Exception e)
{
throw new Exception(Name + "服务启动失败", e);
}
}
4.停止服务
public bool AcceptStop()
{
return (bool)GetManagementObjectInfo("AcceptStop");
} public bool Stop()
{
try
{
if (AcceptStop())
{
GetServiceObject().InvokeMethod("StopService", null);
while (Status() == "Stop Pending") ;
return true;
}
return false;
}
catch (Exception e)
{
throw new Exception(Name + "服务停止失败", e);
}
}