Vivian River
Vivian River

Reputation: 32390

Is there a convenient way to refer to arbitrary registry keys in .net?

I'm working on a .net application that will be used for auditing the configuration of each computer that it runs on.

I would like to be able to read the value of any registry key specified by a string, for example: HKEY_LOCAL_MACHINE\SOFTWARE\MyOrganization\MyProgram

In order to get a handle on this key in .net, I write the following:

RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\MyOrganization\\MyProgram);

As you can see, I have refer to HKEY_LOCAL_MACHINE using Registry.LocalMachine.

Is there a way to refer to registry keys by name without having to refer to these fields in the Registry object?

Upvotes: 0

Views: 120

Answers (3)

Vivian River
Vivian River

Reputation: 32390

I finally figured it out on my own after asking the question :-)

Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyOrganization\MyProgram", "ValueName", "default value");

Furthermore, the documentation says that in the event that the key doesn't exist, the function will return null. This looks useful for using this function to detect the presence or absence of a registry key. (which is very useful for detecting if certain applications are installed)

Upvotes: 0

Guvante
Guvante

Reputation: 19203

You will probably want to split your configuration settings up by type anyway. After all unless you run your application in the context of the user who normally logs into the computer checking HKEY_CURRENT_USER is a waste of time. If you instead specified Machine, Classes, and User, you could check those in the context of the appropriate user.

Alternatively if you aren't looking for any of the fancy functionality and are okay with strings Registry.GetValue/Registry.SetValue work.

Upvotes: 1

Samuel Slade
Samuel Slade

Reputation: 8613

I believe you can use the Registry.GetValue(...) method. The first parameter is the full key name, including the root.

Upvotes: 3

Related Questions