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
string[] strings = {"One", "Two", "Three"}; Registry. SetValue(keyName, "TestArray", strings); // Your default value is returned if the name/value pair // does not exist. string noSuch = (string) Registry. GetValue(keyName, "NoSuchName", "Return this default if NoSuchName does not exist."); Console.
You can consider registry keys are folders in your windows system. Note that a key can have sub keys - much the same way a folder can contain sub folders inside it. To work with the Windows Registry using C#, you can take advantage of the Registry class in the Microsoft. Win32 namespace.
You can search online via number plate sales specialist websites – like us right here at New Reg. Simply enter the exact registration you want to enquire about into the search box, and if it is available then the plate and price for it will show right at the top of the list of options.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With