获取已安装程序的名称,其版本和安装日期WMI C#

时间:2018-07-10 11:18:19

标签: c# wmi

我正在尝试获取有关安装在远程设备上的程序的信息。此刻,我找到了一种输出所有已安装程序的方法。有没有办法获取安装的版本和日期?

        List<string> programs = new List<string>();

        ConnectionOptions connectionOptions = new ConnectionOptions();
        connectionOptions.Username = "USERNAME";
        connectionOptions.Password = "USERPASS";
        //connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
        string devicename = textBox8.Text;
        ManagementScope scope = new ManagementScope("\\\\" + devicename + "\\root\\CIMV2", connectionOptions);
        scope.Connect();

        string softwareRegLoc = @"Software\Microsoft\Windows\CurrentVersion\Uninstall";

        ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
        ManagementBaseObject inParams = registry.GetMethodParameters("EnumKey");
        inParams["hDefKey"] = 0x80000002;//HKEY_LOCAL_MACHINE
        inParams["sSubKeyName"] = softwareRegLoc;

        // Read Registry Key Names 
        ManagementBaseObject outParams = registry.InvokeMethod("EnumKey", inParams, null);
        string[] programGuids = outParams["sNames"] as string[];

        foreach (string subKeyName in programGuids)
        {
            inParams = registry.GetMethodParameters("GetStringValue");
            inParams["hDefKey"] = 0x80000002;//HKEY_LOCAL_MACHINE
            inParams["sSubKeyName"] = softwareRegLoc + @"\" + subKeyName;
            inParams["sValueName"] = "DisplayName";
            // Read Registry Value 
            outParams = registry.InvokeMethod("GetStringValue", inParams, null);

            if (outParams.Properties["sValue"].Value != null)
            {
                string softwareName = outParams.Properties["sValue"].Value.ToString();
                programs.Add(softwareName);
            }
        }

        foreach (string softwareName in programs)
        {
            int n = dataGridView8.Rows.Add();
            dataGridView8.Rows[n].DefaultCellStyle.BackColor = Color.LightGreen;
            dataGridView8.Rows[n].Cells[0].Value = devicename;
            dataGridView8.Rows[n].Cells[1].Value = softwareName;
            dataGridView8.FirstDisplayedScrollingRowIndex = dataGridView8.RowCount - 1;
        }
    }
    catch
    {
        MessageBox.Show("Something went wrong");
    } 
}

1 个答案:

答案 0 :(得分:1)

欢迎使用堆栈溢出。使用ORMi库轻松获取该信息:

1)通过NuGet安装:

Install-Package ORMi

2)使用库:

using ORMi;

3)实例化并使用:

WMIHelper helper =新的WMIHelper(“ root \ CimV2”);

var programs = helper.Query("SELECT Name, Version, InstallDate FROM Win32_Product").ToList();

foreach(var p in programs)
{
    Console.WriteLine(p.Name);
}

就是这样。然后,如果您想进行更高级的工作,则可以定义模型类并以更简单的方式查询。您可以在GitHub上阅读文档。