Saturday, July 27, 2013

How to read/write value from registry using C#.Net?

 In the winform some time we need to access the registry value or we need to modify the registry value to store or get some important information. For that in C# have simple option to handle the registry read/write using Microsoft.Win32.RegistryKey namespace. The below two methods will explain how to read key value from the local registry.


Save Value to Registory:
The WriteToRegistry method will write the value to registry based on Keyname. The Keyname must be exist before in the registry.


 public static void WriteToRegistry(string keyname, string keyvalue)
        {
            Microsoft.Win32.RegistryKey MainRootKey = null;
            Microsoft.Win32.RegistryKey subKey = null;                        
            try
            {
                MainRootKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE "true);
                if (MainRootKey!= null)
                {
                    subKey = rootKey.OpenSubKey("MyApplication"true);                  
                    if (subKey != null)
                    {
                        subKey.SetValue(keyname, keyvalue);
                        subKey.Close();
                        
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (subKey != null)
                    subKey.Close();
                subKey = null;
 
                if (MainRootKey != null)
                    MainRootKey.Close();
                MainRootKey = null;
            }
 
        }
 
 
How to read MyApplication Registry information using C#.net ?

 The GetFromRegistry Method will return the registry value based on the KeyName. The Keyname should be exist before in the registry.
 
 


private string GetFromRegistry(string keyname)
        {
            string strReturn = string.Empty;
            RegistryKey objReg = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("MyApplication");
            if (objReg != null && objReg.GetValue(keyname) != null)
                strReturn = objReg.GetValue(keyname).ToString();
 
            return strReturn;
 
        }
 

No comments: