0

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

E235
  • 11,560
  • 24
  • 91
  • 141
  • Looks like an extension method. In which case you don't explicitly pass the first parameter, in this instance `key`. That's implicitly passed with the object you call the method on. – sticky bit Jan 09 '22 at 15:42
  • 1
    Use one of the static members of the `Registry` class, see https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registry – Anand Sowmithiran Jan 09 '22 at 15:45

1 Answers1

2

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.
Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • Thank you, for the explanation, it works. I didn't want to comment this on the previous question as I considered it as a separate question that can maybe help other. Thank you! – E235 Jan 09 '22 at 15:48