C# Registry Operations

The registry is an optimal location for saving information about your application as well as individual user settings.

The Registry comprises a number of logical sections called Hives. The following are the predefined keys that are used by the system.

  1. HKEY_CURRENT_USER
  2. HKEY_USERS
  3. HKEY_LOCAL_MACHINE
  4. HKEY_CLASSES_ROOT
  5. HKEY_CURRENT_CONFIG

Each key has many subkeys and may have a value.

When programming in C#, you can choose to access the registry via either the functions provided by C# or the registry classes of the .NET Framework. The operations on the registry in .NET can be done using two classes of the Microsoft.Win32 Namespace: Registry class and the RegistryKey class. The Registry class provides base registry keys as shared public methods:

using Microsoft.Win32;

Creating a Registry Entry

rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); rKey.CreateSubKey("AppReg");

Above code shows how to create a subkey under HKLM\Software called AppReg.

Deleting a Subkey

rKey = Registry.LocalMachine.OpenSubKey("Software", true); rKey.DeleteSubKey("AppReg", true);

The following C# program shows how to create a registry entry , set values to registry entries, retrieve values from registry and delete keys on Registry. Drag and drop four buttons on the form control and copy and paste the following source code.

Full Source C#
using System; using System.Data; using System.Windows.Forms; using Microsoft.Win32; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { RegistryKey rKey ; rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); rKey.CreateSubKey("AppReg"); rKey.Close(); MessageBox.Show ("AppReg created !"); } private void button2_Click(object sender, EventArgs e) { RegistryKey rKey ; rKey = Registry.LocalMachine.OpenSubKey("Software\\AppReg", true); rKey.SetValue("AppName", "RegApp"); rKey.SetValue("Version", 1.1); rKey.Close(); MessageBox.Show("Appname , version created"); } private void button3_Click(object sender, EventArgs e) { RegistryKey rKey ; Object ver ; string app = null; rKey = Registry.LocalMachine.OpenSubKey("Software\\AppReg", true); app = (string)rKey.GetValue("AppName"); ver = rKey.GetValue("Version"); rKey.Close(); MessageBox.Show("App Name " + app + " Version " + ver.ToString()); } private void button4_Click(object sender, EventArgs e) { RegistryKey rKey ; rKey = Registry.LocalMachine.OpenSubKey("Software", true); rKey.DeleteSubKey("AppReg", true); rKey.Close(); MessageBox.Show("AppReg deleted"); } } }