简体   繁体   中英

looking for registry read through WMI

I am trying to get my application version and I am able to do for local machine using below code,

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());
        }

Now, I need to read for remote machine and above piece of code is not working, so looking for a WMI solution?

Can we do it through WMI way?

You can use the Win32_Product Class from WMI. Then use the namespace Microsoft.Management.Infrastructure to read out remotly with C#( https://docs.microsoft.com/en-us/windows/desktop/wmisdk/connecting-to-wmi-on-a-remote-computer ). This is an easy and good way to read out WMI remotly. I used it like this on my WMI-program:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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