Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C#
Article

Copy and Rename Registry Keys

Rate me:
Please Sign up or sign in to vote.
3.42/5 (19 votes)
11 Nov 2006CPOL2 min read 78K   1.1K   12   8
A utility that will copy and rename registry keys

Background

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.

Overview

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 public methods:

  • CopyKey
  • RenameSubKey

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 private method: RecurseCopyKey.

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.

The Demo

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.

The Code

Here is a copy of the entire RegistryUtilities.cs file:

C#
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

// RenameRegistryKey © Copyright 2006 Active Computing
namespace RenameRegistryKey
{
    public class RegistryUtilities
    {
        /// <summary>
        /// Renames a subkey of the passed in registry key since 
        /// the Framework totally forgot to include such a handy feature.
        /// </summary>
        /// <param name="regKey">The RegistryKey that contains the subkey 
        /// you want to rename (must be writeable)</param>
        /// <param name="subKeyName">The name of the subkey that you want to rename
        /// </param>
        /// <param name="newSubKeyName">The new name of the RegistryKey</param>
        /// <returns>True if succeeds</returns>
        public bool RenameSubKey(RegistryKey parentKey, 
			string subKeyName, string newSubKeyName)
        {
            CopyKey(parentKey, subKeyName, newSubKeyName);
            parentKey.DeleteSubKeyTree(subKeyName);
            return true;
        }

        /// <summary>
        /// Copy a registry key.  The parentKey must be writeable.
        /// </summary>
        /// <param name="parentKey"></param>
        /// <param name="keyNameToCopy"></param>
        /// <param name="newKeyName"></param>
        /// <returns></returns>
        public bool CopyKey(RegistryKey parentKey, 
			string keyNameToCopy, string newKeyName)
        {
            //Create new key
            RegistryKey destinationKey = parentKey.CreateSubKey(newKeyName);

            //Open the sourceKey we are copying from
            RegistryKey sourceKey = parentKey.OpenSubKey(keyNameToCopy);

            RecurseCopyKey(sourceKey, destinationKey);

            return true;
        }

        private void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey)
        {
            //copy all the values
            foreach (string valueName in sourceKey.GetValueNames())
            {        
                object objValue = sourceKey.GetValue(valueName);
                RegistryValueKind valKind = sourceKey.GetValueKind(valueName);
                destinationKey.SetValue(valueName, objValue, valKind);
            }

            //For Each subKey 
            //Create a new subKey in destinationKey 
            //Call myself 
            foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames())
            {
                RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName);
                RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName);
                RecurseCopyKey(sourceSubKey, destSubKey);
            }
        }
    }
}

I hope this is useful for you.

History

  • 11th November, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionEnvironment names Pin
mikolka2216-Jun-19 22:07
mikolka2216-Jun-19 22:07 
QuestionPermission Issue Pin
babakin2-Nov-13 17:12
babakin2-Nov-13 17:12 
QuestionThanks Pin
lakshman rao10-Feb-13 18:44
lakshman rao10-Feb-13 18:44 
GeneralHelpful article. I needed to chance the name of the string value ... Here is the code for who needs.. Pin
gmu0422-Apr-11 3:48
gmu0422-Apr-11 3:48 
GeneralMy vote of 4 Pin
mostwanted425-Oct-10 9:11
mostwanted425-Oct-10 9:11 
GeneralProblem Pin
edb200031-Mar-08 13:08
edb200031-Mar-08 13:08 
GeneralRe: Problem Pin
fallafab26-Sep-09 15:12
fallafab26-Sep-09 15:12 
Or you can also open your key in a "using" block so the key object is disposed after use.
Also, you should make this class and its methods static so you can use them without having to create a new instance of the RegistryUtilities class.

Following is the updated code:

public static class RegistryUtilities
{
/// <summary>
/// Renames a subkey of the passed in registry key since
/// the Framework totally forgot to include such a handy feature.
/// </summary>
/// <param name="regKey">The RegistryKey that contains the subkey
/// you want to rename (must be writeable)</param>
/// <param name="subKeyName">The name of the subkey that you want to rename
/// </param>
/// <param name="newSubKeyName">The new name of the RegistryKey</param>
/// <returns>True if succeeds</returns>
public static bool RenameSubKey(RegistryKey parentKey,
string subKeyName, string newSubKeyName)
{
CopyKey(parentKey, subKeyName, newSubKeyName);
parentKey.DeleteSubKeyTree(subKeyName);
return true;
}

/// <summary>
/// Copy a registry key. The parentKey must be writeable.
/// </summary>
/// <param name="parentKey"></param>
/// <param name="keyNameToCopy"></param>
/// <param name="newKeyName"></param>
/// <returns></returns>
public static bool CopyKey(RegistryKey parentKey,
string keyNameToCopy, string newKeyName)
{
//Create new key
using (RegistryKey destinationKey = parentKey.CreateSubKey(newKeyName))
{
//Open the sourceKey we are copying from
using (RegistryKey sourceKey = parentKey.OpenSubKey(keyNameToCopy))
{
RecurseCopyKey(sourceKey, destinationKey);
}
}
return true;
}

private static void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey)
{
//copy all the values
foreach (string valueName in sourceKey.GetValueNames())
{
object objValue = sourceKey.GetValue(valueName);
RegistryValueKind valKind = sourceKey.GetValueKind(valueName);
destinationKey.SetValue(valueName, objValue, valKind);
}

//For Each subKey
//Create a new subKey in destinationKey
//Call myself
foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames())
{
using (RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName))
{
using (RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName))
{
RecurseCopyKey(sourceSubKey, destSubKey);
}
}
}
}
}


Anyway, thanks very much for this code, it's very useful and nicely done!
Generalnice Pin
Harkamal Singh23-Jul-07 2:22
Harkamal Singh23-Jul-07 2:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.