Assaf
Assaf

Reputation: 1346

How to add nested Registry Key/Value in C#?

Given a registry path "\a\b\c\d", I would like to add a value to key 'd'. The catch is - I don't know whether a,b, or c even exist, and I want the code to generate them if they do not exist. Is there a quick way (using some .NET method I haven't seen) to do this? I could go the route of iterating through registry keys and use the OpenSubKey/GetValue/SetValue methods to perform the process, but would like to avoid reinventing the wheel if I can...

N.B.: The behavior I am looking for is the same behavior you would get from running a .reg file (it will create the necessary subkeys).

Thanks,

Assaf

Upvotes: 9

Views: 8890

Answers (2)

James King
James King

Reputation: 6343

I don't know of a built-in, single call you can make to do this. However, you don't need to call OpenSubKey/GetValue, etc. A call to CreateSubKey will create a new key, or open the existing key if it exists.

RegistryKey regKey = startingRootKey;
string[] RegKeys = pathToAdd.split('\'');
foreach (string key in RegKeys) {
    regKey = regKey.CreateSubKey(key);
}
regKey.SetValue("ValueName", "Value");

Ignore the extra ' in there, I needed it to make the formatting look right. ??

Also, be sure you test for exceptions when doing registry key adds... there's a lot security- and path-wise that could go wrong. A list of exceptions to trap is here.


EDIT
I'm making this too complicated! I just tested... the following will do exactly what you want:

RegistryKey regKey = startingRootKey;
regKey = regKey.CreateSubKey(@"a\b\c\d");
regKey.SetValue("ValueName", "Value");
regKey.Close();

It's smart enough to parse the nested path. Just make sure you have the @ symbol, or it will treat the string is as if it were escaped.

Upvotes: 19

Hans Olsson
Hans Olsson

Reputation: 55009

I don't think there's anything built in, but doing a string split on the registry path and then looping through it and doing CreateSubKey (instead of OpenSubKey so it creates missing ones) on each part is ok in my view.

Upvotes: 0

Related Questions