繁体   English   中英

寻找通过WMI读取注册表

[英]looking for registry read through WMI

我正在尝试获取我的应用程序版本,并且能够使用以下代码在本地计算机上运行,

try
        {
            string path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";

            RegistryKey key = null;

            if (!string.IsNullOrEmpty(path))
            {
                //get the 64-bit view first
                key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                key = key.OpenSubKey(path);

                //Couldn't find the value in the 64-bit view so grab the 32-bit view
                if (key == null)
                {
                    key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                    key = key.OpenSubKey(path);
                }
            }


            foreach (string tempKeyName in key.GetSubKeyNames())
            {
                RegistryKey tempKey = key.OpenSubKey(tempKeyName + "\\InstallProperties");
                if (tempKey != null)
                {
                    if (string.Equals(Convert.ToString(tempKey.GetValue("DisplayName")), "My Application", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Console.WriteLine(Convert.ToString(tempKey.GetValue("DisplayVersion")));
                        break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

现在,我需要阅读远程机器,并且上面的代码无法正常工作,因此正在寻找WMI解决方案吗?

我们可以通过WMI方式吗?

您可以使用WMI中的Win32_Product类。 然后使用命名空间Microsoft.Management.Infrastructure通过C#远程读取( https://docs.microsoft.com/zh-cn/windows/desktop/wmisdk/connecting-to-wmi-on-a-remote-computer ) 。 这是一种远程读取WMI的简便方法。 我在WMI程序中这样使用它:

using (var cimSession = CimSession.Create(computername))
{
    var select = $"SELECT Version FROM  Win32_Product WHERE Name = 'AppName'";

    var allVolumes = cimSession.QueryInstances(@"root\cimv2", "WQL", select);

    double value = 0;
    var cimInstances = allVolumes.ToList();
    if (!cimInstances.Any())
        throw new CimException($"No Values to read");

    foreach (var volume in cimInstances)
        value = Convert.ToDouble(volume.CimInstanceProperties["Version"].Value);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM