Sunday, June 5, 2011

How to rename a registry key with .NET

Let’s say I have a registry key named “HKEY_CURRENT_USER\SOFTWARE\JTB World 1” and I want to rename it to “HKEY_CURRENT_USER\SOFTWARE\JTB World 2”. This is easily done in the Registry Editor (regedit.exe).

But neither Microsoft.Win32.Registry class nor .NET Framework My.Computer.Registry provide rename functionality.

One solution is using REG.EXE, copying the key and all subkeys and then delete the old key. No need to recursively copy keys as would be needed if using the Registry class.

Here is a VB.NET example that easily can be converted to for example C#, BAT/CMD/VBS (VBScript). No error checking added. WindowStyle is used to avoid seeing Windows command window showing.

Dim OldKey As String = "HKEY_CURRENT_USER\SOFTWARE\JTB World 1"
Dim NewKey As String = "HKEY_CURRENT_USER\SOFTWARE\JTB World 2"
Dim startInfo As New ProcessStartInfo("REG.EXE")
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.Arguments = "COPY """ & OldKey & """ """ & NewKey & """ /s"
Dim myProcess As Process = Process.Start(startInfo)
myProcess.WaitForExit()
startInfo.Arguments = "DELETE """ & OldKey & """ /f"
Process.Start(startInfo)

2 comments:

  1. This technique is not safe, because there is no guarantee that the old keys get copied before they are deleted.

    ReplyDelete
  2. Correct Owen. I forgot to add WaitForExit. Now it should be safer even though there still is no error checking that the copying really works.

    ReplyDelete