C# Read And Write A Registry Key
This example shows how to read and write a registry key. To do this, we must use RegistryKey and Registry classes in Microsoft.Win32 namespace.
Usage:
//Usage: Write("REGISTRY DATA1", "http://www.csharpexamples.com"); Write("REGISTRY DATA2", 123.ToString()); string registryData1 = Read("REGISTRY DATA1"); string registryData2 = Read("REGISTRY DATA2");
Sample Read and Write Methods:
////// This C# code reads a key from the windows registry. /// /// ///public string Read(string keyName) { string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper(); RegistryKey sk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subKey); if (sk == null) return null; else return sk.GetValue(keyName.ToUpper()).ToString(); } /// /// This C# code writes a key to the windows registry. /// /// /// public void Write(string keyName, string value) { string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper(); RegistryKey sk1 = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subKey); sk1.SetValue(keyName.ToUpper(), value); }