Update: This tutorial has been slightly rewritten, and source code/demo application has been added.
Important Note: This article does not take into account Windows User Account Control (UAC). You may need to run the code with administrator rights if you have UAC switched on.
[Summary]Having the ability to export (and import) registry keys in C# can be very important. I myself found recently the need to back up the registry to a physical file so that it could be retrieved later if something went wrong.[/Summary] There is plenty of code around the web to do this, but I found that some can be messy and most make use of the Microsoft.VisualBasic namespace, which I always try to avoid.
This code was originally inspired by Michael Freidgeims blog, but has been revised several times and is now significantly different.
Download C# source code and demo application. (Visual Studio 2010 or Visual C# Express 2010)
As the Registry Editor (regedit.exe) has a built in Export command, all we need to do is call it and pass some arguments. The command we need to pass looks like this;
"/e " + path + " " + key
/e is the export command
path is the physical location on the hard drive in which to save the registry keys to a file (“My Backup.reg”)
key is the logical registry key to export
Start by creating a single method called “ExportKey” that will take care of the entire export process;
public void ExportKey(string RegKey, string SavePath)
string path = "\"" + SavePath + "\"";
string key = "\"" + RegKey + "\"";
Process proc = new Process();
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.UseShellExecute = false;
proc = Process.Start("regedit.exe", "/e " + path + " " + key + "");
if (proc != null) proc.WaitForExit();
if (proc != null) proc.Dispose();
MessageBox.Show("The export process is complete.\n\nCheck your desktop or the folder that you have specified as your save location.");
There are a couple of things going on here; (in this order)
- Create a process that we can use to “call” the Registry Editor
- Tell the operating system not to use ShelExecute
- Start the process, with the path to the Registry Editor (regedit.exe) and the aforementioned export command
- Wait until the process automatically closes
- Kill the resources
- Tell the end user
Now to call the method, all we have to do is pass the path of the registry key we want to export, and the path of where we want to export it to;
ExportKey("HKEY_CURRENT_USER\\", Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Exported HKCU.reg");
And that’s all there is to it. Be sure to download the demo application and source code (above) for more information.