Thursday, April 20, 2017

Read and Write in registry from c#

Before start to learn how to edit the registry a quick 
Open Registry window
1) Press CRTL+ R
2) run window will open.
3) type command "regedit"


4)and press enter , below window get open



Come back to original topic

.Net provide the class RegistryKey it is in Microsoft.Win32 namespace

below is the types to read different base key

  • 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.

1. 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");
            }