减少WMI查询执行时间

van*_*gos 4 c# wmi-query execution-time

在我的应用程序中,我想看看Windows 7是否被激活.要清楚,我不想检查窗户是否是正品.我使用下面的代码,在这里找到http://www.dreamincode.net/forums/topic/166690-wmi-softwarelicensingproduct/

执行查询所需的时间约为5-10秒.反正有没有减少所需的时间?或者另一种检查winows 7是否被激活的方法?

public string VistaOrNewerStatus(){
string status = string.Empty;
string computer = ".";
try
{
    //set the scope of this search
    ManagementScope scope = new ManagementScope(@"\\" + computer + @"\root\cimv2");
    //connect to the machine
    scope.Connect();

    //use a SelectQuery to tell what we're searching in
    SelectQuery searchQuery = new SelectQuery("SELECT * FROM SoftwareLicensingProduct");

    //set the search up
    ManagementObjectSearcher searcherObj = new ManagementObjectSearcher(scope, searchQuery);

    //get the results into a collection
    using (ManagementObjectCollection obj = searcherObj.Get())
    {
        MessageBox.Show(obj.Count.ToString());
        //now loop through the collection looking for
        //an activation status
        foreach (ManagementObject o in obj)
        {

            //MessageBox.Show(o["ActivationRequired"].ToString());
            switch ((UInt32)o["LicenseStatus"])
            {
                case 0:
                    status = "Unlicensed";
                    break;
                case 1:
                    status = "Licensed";
                    break;
                case 2:
                    status = "Out-Of-Box Grace Period";
                    break;
                case 3:
                    status = "Out-Of-Tolerance Grace Period";
                    break;
                case 4:
                    status = "Non-Genuine Grace Period";
                    break;
            }
        }
    }


   // return activated;
}
catch (Exception ex)
{
   // MessageBox.Show(ex.ToString());
    status = ex.Message;
    //return false;
}
return status;
Run Code Online (Sandbox Code Playgroud)

}

Han*_*ans 6

我建议只查询你真正需要的属性.因此,如果您只需要WMI类的LicenseStatus值,SoftwareLicensingProduct则使用以下查询:

SelectQuery searchQuery = new 
            SelectQuery("SELECT LicenseStatus FROM SoftwareLicensingProduct");
Run Code Online (Sandbox Code Playgroud)

这应该可以改善您的表现.正如DJ KRAZE在答案中指出的那样,你当然应该处理你的管理课程.

在我的Windows 7机器上仅使用查询中的LicenseStatus属性花了246ms.查询所有属性(使用"*")需要2440毫秒.