预备知识:
- WMI(Windows Management Instrumentation)是内置在 Windows 系列操作系统中核心的管理支持技术,目前WMI 已经是一种规范和基础结构,通过它可以访问、配置、管理和监视几乎所有的 Windows 资源例如磁盘、事件日志、文件、文件夹、文件系统、网络组件、操作系统设置、性能数据、打印机、进程、注册表设置等等。
- WQL(WMI Query Language)就是内置在WMI中的查询语言,它是 SQL 的一个子集。
本文介绍的是WMI的一个小应用:查看当前操作系统是64位的还是32位的。
为了运行这段代码,需要:
- 在Project的reference中添加System.Management的引用;
- 需要在C#源代码文件中添加对System.Management这个namespace的引用。
using System.Management;
代码如下:
/// <summary>
/// Gets OS address width.
/// </summary>
/// <returns>32 indicates 32-bit OS, and 64 indicates 64-bit OS.</returns>
public static UInt16 GetOSAddressWidth()
{
try
{
SelectQuery query = new SelectQuery("select AddressWidth from Win32_Processor");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = searcher.Get();
foreach (ManagementObject mo in moCollection)
{
foreach (PropertyData property in mo.Properties)
{
if (property.Name.Equals("AddressWidth"))
{
return Convert.ToUInt16(property.Value);
}
}
}
throw new Exception("Didn't get expected query result from WMI.");
}
catch (Exception ex)
{
throw new Exception("Error occurs in WMI query.", ex.InnerException);
}
}
在32位Windows操作系统中,这个函数返回32;在64位Windows操作系统中,这个函数返回64。
目前尚未遇到抛出Exception的情况,除非当前的操作系统不是Windows,或者是比Windows 95还早的Windows(例如Windows 3.1?)。
不过我认为我确实应该考虑一下Mono on Linux上的情形。
参考文献:
- Windows Management Instrumentation http://msdn.microsoft.com/en-us/library/aa394582%28v=VS.85%29.aspx
- WMI Queries http://msdn.microsoft.com/en-us/library/ms186146%28v=vs.80%29.aspx
- Using WMI Class in C# http://www.dreamincode.net/forums/topic/42934-using-wmi-class-in-c%23/
- Win32_Processor class http://msdn.microsoft.com/en-us/library/aa394373.aspx
- Win32_OperatingSystem class http://msdn.microsoft.com/en-us/library/aa394239.aspx
- Win32_Processor WMI 类的系列属性返回不正确的值在一台基于 Windows Server 2003 的计算机运行一些处理器 http://support.microsoft.com/kb/924779/zh-cn