Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Tuesday, November 14, 2006

Handling Registry in .NET

Copy and Rename registry keys / Handling Registry in .NET

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 frame work 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);


            return true;


        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);





End of Handling Registry in .NET

Post a Comment