Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get values of registry subkeys

Tags:

c#

registry

I have something like that in registry:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MyKeys\Keys1
  > random subkey 1 / value a = 1
  > random subkey 2 / value b = 2
  > random subkey 3 / value c = 3
  > random subkey 4 / value d = 4

random subkey x - random numbers (for eg {6E7EE186-9G13-50HC-A001-319DA68183A7})

Now I want to save all of subkeys names to string[] and then add each value to listView:

a | 1
b | 2
c | 3
d | 4

Can someone help me with this?

like image 974
randomuser1337 Avatar asked Dec 11 '22 23:12

randomuser1337


1 Answers

This code is an example to retreive subkeys + values from specific key

    class Key
    {
        public string KeyName { get; set; }
        public List<KeyValuePair<string, object>> Values { get; set; }
    }

    private List<Key> GetSubkeysValue(string path, RegistryHive hive)
    {
        var result = new List<Key>();
        using (var hiveKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default))
        using (var key = hiveKey.OpenSubKey(path))
        {
            var subkeys = key.GetSubKeyNames();

            foreach (var subkey in subkeys)
            {
                var values = GetKeyValue(hiveKey, subkey);
                result.Add(values);
            }
        }
        return result;
    }

    private Key GetKeyValue(RegistryKey hive, string keyName)
    {
        var result = new Key() {KeyName = keyName};
        using (var key = hive.OpenSubKey(keyName))
        {
            foreach (var valueName in key.GetValueNames())
            {
                var val = key.GetValue(valueName);
                var pair = new KeyValuePair<string, object>(valueName, val);
                result.Values.Add(pair);
            }
        }

        return result;
    }

call GetKeyValue with your root path(SOFTWARE\Microsoft\Windows\CurrentVersion\MyKeys\Keys1 in your question) and local machine hive

Notes:

There are cases where OpenSubKey return null, in my example those cases will throw NullRefrenceException => you should decide what will happen when OpenSubKey return null

Your path is in local_machine - software, make sure that you are using the right RegistryView

like image 160
Old Fox Avatar answered Dec 25 '22 04:12

Old Fox