我在C#中使用WMI来获取所有已安装的软件,但它并不显示只有Microsoft软件的所有软件

时间:2013-10-30 15:53:13

标签: c# wmi impersonation wmi-query

  public ManagementScope GetScope()
    {
        try
        {
            //string classScope="winmgmts:" + "{impersonationLevel=impersonate}!\\" + strComputer + "\\root\\cimv2";
            string serverString = @"root\cimv2";

            ManagementScope scope = new ManagementScope(serverString);


                ConnectionOptions options = new ConnectionOptions
                {
                    Impersonation = ImpersonationLevel.Impersonate,
                    Authentication = AuthenticationLevel.Connect,
                    EnablePrivileges = true
                };
                scope.Options = options; 

            return scope; 
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }
    }

    public void InvokeMethodsFunctions1()
    {
        ManagementScope mScope = GetScope();

        mScope.Connect();

        if (mScope.IsConnected)
        {
            ManagementClass processClass =
                new ManagementClass(mScope.Path);
            ManagementObjectSearcher mos = new ManagementObjectSearcher(mScope, new ObjectQuery("SELECT * FROM Win32_Product"));
            //get collection of WMI objects
            ManagementObjectCollection queryCollection = mos.Get();

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"Result.txt"))
            {
                textBox1.Text = "";
                //enumerate the collection.
                foreach (ManagementObject m in queryCollection)
                {
                    // access properties of the WMI object
                    string line = " " + m["Name"] + " , InstallDate : " + m["InstallDate"] + " LocalPackage : " + m["LocalPackage"];
                    Console.WriteLine(line);
                    file.WriteLine(line);
                    textBox1.Text += line + "\n";
                }
            }

       }

    }

我的代码中有什么问题?

2 个答案:

答案 0 :(得分:2)

没有错,Win32_Product WMI类仅列出Windows Installer安装的产品(MSI)。

答案 1 :(得分:1)

我刚刚测试了以下代码的简化版本,我看到我的电脑上安装了所有内容,甚至是我自己编写和安装的服务:

var products = new ManagementObjectSearcher(new ObjectQuery("SELECT * FROM Win32_Product"));
var result = products.Get();

foreach (var product in result)
{
    Console.WriteLine(product.GetPropertyValue("Name").ToString());
}

Console.ReadLine();

看起来你正在缩小查询范围,这可能就是为什么你没有看到所有内容,试试上面的内容,看看你是否有更多运气。