Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading