WMI .NET API

在.NET中我们使用标准的WMI查询语句查询电脑上的相关信息。WQL是SQL的一个子集。在.NET中所有相关的类(如ManagementObjectSearcher)封装在System.Management命名空间中。具体参考MSDN相关帮助文档http://msdn.microsoft.com/en-us/library/ms186146.aspx

本文将采用C#检测电脑上安装的杀毒软件信息。

WMI Administrative Tools

为了保证查询到相关的信息,请先安装WML管理工具WMI Administrative Tools。安装后使用WMI Object Browser来检测你需要查找的实例是否存在或者路径是否正确。

如下图所示,在我的PC上我的杀毒软件信息存在路径是root\SecurityCenter2 而非 root\SecurityCenter

image

C#代码查询

使用以下代码即可查询出相关的信息:

   1:  private static void UsingWMI()
   2:          {
   3:              WqlObjectQuery wqlQuery = new WqlObjectQuery("SELECT * FROM AntiVirusProduct");
   4:   
   5:              string computer = Environment.MachineName;   
   6:              string path = @"\\" + computer + @"\root\SecurityCenter2";   
   7:   
   8:              ManagementScope scope = new ManagementScope
   9:              {
  10:                  Path = new ManagementPath(path)
  11:              };
  12:              ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, wqlQuery);
  13:   
  14:              ManagementObjectCollection instances = searcher.Get();
  15:              foreach (ManagementObject obj in instances)
  16:              {
  17:                  foreach (var property in obj.Properties)
  18:                  {
  19:                      Console.WriteLine("{0}:{1}", property.Name, property.Value);
  20:                  }
  21:              }
  22:          }

在我的PC上可以查询出我安装了Avast以及Windows Defender.

image

About author
Disclaimer
The opinions and comments expressed herein are my own personal opinions and do not represent my employer's view in any way.
Comments
No comments.
Add comment
Title
Title is required.
Name
Name is required.
Email
Please input your personal email with valid format.
Comments
Please input comment content.
Captcha Refresh
Input captcha:

Subscription

Statistics

Locations of visitors to this page