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

2
  • 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. Commented Jan 9, 2022 at 15:42
  • 1
    Use one of the static members of the Registry class, see learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registry Commented Jan 9, 2022 at 15:45

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.