Search code examples
c#winapiregistryregistrykey

How to initialize RegistryKey variable


I have a function (OpenSubKeySymLink) that receives this kind of variable: this RegistryKey key.
I don't know how to initialize it and pass it to the function.


public static RegistryKey OpenSubKeySymLink(this RegistryKey key, string name, RegistryRights rights = RegistryRights.ReadKey, RegistryView view = 0)
{
    var error = RegOpenKeyExW(key.Handle, name, REG_OPTION_OPEN_LINK, ((int)rights) | ((int)view), out var subKey);
    if (error != 0)
    {
        subKey.Dispose();
        throw new Win32Exception(error);
    }
    return RegistryKey.FromHandle(subKey);  // RegistryKey will dispose subKey
}


static void Main(string[] args)
{
    RegistryKey key;  // how to initialize it?
    OpenSubKeySymLink(key, @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\myKey", RegistryRights.ReadKey, 0);
}


Solution

  • I apologize, I didn't fully explain how to use this code in my previous answer.

    I wrote it as an extension, so you can call it on either an existing sub-key, or on one of the main keys, such as Registry.CurrentUser.

    You would use it like this for example:

    using (var key = Registry.CurrentUser.OpenSubKeySymLink(@"SOFTWARE\Microsoft\myKey", RegistryRights.ReadKey))
    {
        // do stuff with key
    }
    

    You can obviously still use it as a non-extension function

    using (var key = OpenSubKeySymLink(Registry.CurrentUser, @"SOFTWARE\Microsoft\myKey", RegistryRights.ReadKey))
    {
        // do stuff with key
    }
    
    • Note the optional parameters, which means that some parameters don't need to be passed as they have defaults.
    • Note the use of using on the returned key, in order to dispose it correctly.