Author : Admin
Last Modified : 17-Oct-2021
Complexity : Beginner

Read and Write in registry from C#


Before starting to learn how to edit the registry a quick 
Open Registry window

  • Press CRTL+ R
  • run window will open.
  • type command "regedit"
  • and press enter, below the window, get open

 

Come back to the original topic .Net provide the class RegistryKey it is in Microsoft.Win32 namespace. below are the types to read different base keys.

  • ClassesRoot
  • CurrentConfig
  • CurrentUser
  • DynData
  • LocalMachine
  • PerformanceData
  • Users

ClassesRoot : Defines the types (or classes) of documents and the properties associated with those types. This field reads the Windows registry base key HKEY_CLASSES_ROOT.

CurrentConfig : Contains configuration information pertaining to the hardware that is not specific to the user. This field reads the Windows registry base key HKEY_CURRENT_CONFIG.

CurrentUser : Contains information about the current user preferences. This field reads the Windows registry base key HKEY_CURRENT_USER

DynData : Contains dynamic registry data. This field reads the Windows registry base key HKEY_DYN_DATA.
"The DynData registry key only works on Win9x, which is no longer supported by the CLR.  On NT-based operating systems, use the PerformanceData registry key instead."

LocalMachine : Contains the configuration data for the local machine. This field reads the Windows registry base key HKEY_LOCAL_MACHINE.

PerformanceData : Contains performance information for software components. This field reads the Windows registry base key HKEY_PERFORMANCE_DATA.

Users : Contains information about the default user configuration. This field reads the Windows registry base key HKEY_USERS.

 

Open the registry Key.

*Suppose we need to open the key and it is under the HKEY_LOCAL_USER

           RegistryKey rk = Registry.CurrentUser;
           string subKey = "tmentor";
           RegistryKey sk = rk.OpenSubKey(subKey);
           if (sk == null)
           {
               // key is not available
               //TODO Code
           }
           else
           {
               // key is available and open
               //TODO Code
           }

 

Add a new Key

           RegistryKey rk = Registry.CurrentUser;
           string subKey = "tmentor";
           RegistryKey sk = rk.OpenSubKey(subKey);
           if (sk == null)
           {
               sk.CreateSubKey("tmentor");
           }

 

Add/Update a new key-value

           RegistryKey rk = Registry.CurrentUser;
           string subKey = "tmentor";
           RegistryKey sk = rk.OpenSubKey(subKey, true);
           if (sk != null)          
           {
               sk.SetValue("IsRegistryAdded", "1");
           }