One day I was writing some code and had the need to work with the Windows registry. I was so happy that I was coding in .NET using C#. "How I love the framework", I was saying to myself. Then all of the sudden, I found that a critical method was missing. I found that I could not simply call a method in the framework to rename a registry key.
To my further amazement, I was surprised that I could not find a code snippet to help do this. I saw a challenge and I was on a mission.
So that is the story of why I wrote this code.
There is not much code to this at all. In fact there is more code in the test form that demonstrates the utility.
Basically what you will find is a solution that contains a form and a class file written in C#. The form has code that sets up and runs the test. The utility code that does the registry key renaming is in a class file named RegistryUtilities.cs.
The utility contains two
The process of renaming a registry key is actually a recursive copy of all the values and sub keys and then a delete of the original key. So when you call
RenameSubKey, it actually calls
CopyKey. The real work is done in the
RecurseCopyKey is responsible for copying all the values and sub keys to a new sub key. The new sub key is placed at the same level in the tree as the one being copied.
Blah, blah, blah… You'll probably get more from seeing the code than from reading anything more I could write here.
There is a demo available for download. If you run the demo, it creates a new registry key under local user and then renames it.
Here is a copy of the entire RegistryUtilities.cs file:
public class RegistryUtilities
public bool RenameSubKey(RegistryKey parentKey,
string subKeyName, string newSubKeyName)
CopyKey(parentKey, subKeyName, newSubKeyName);
public bool CopyKey(RegistryKey parentKey,
string keyNameToCopy, string newKeyName)
RegistryKey destinationKey = parentKey.CreateSubKey(newKeyName);
RegistryKey sourceKey = parentKey.OpenSubKey(keyNameToCopy);
private void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey)
foreach (string valueName in sourceKey.GetValueNames())
object objValue = sourceKey.GetValue(valueName);
RegistryValueKind valKind = sourceKey.GetValueKind(valueName);
destinationKey.SetValue(valueName, objValue, valKind);
foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames())
RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName);
RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName);
I hope this is useful for you.
- 11th November, 2006: Initial post