Search code examples
c#registry

Unable to Overwrite HKEY_CLASSES_ROOT registry value in C#


I am trying to overwrite the below values in registry on existing value of "Default". Written the below code but it is not updating the value. also code is not giving any error.

[HKEY_CLASSES_ROOT\ugmportalfile\Shell\Open\Command] @="\"%TPR%\start_manager.bat\""

RegistryKey regKey=Registry.ClassesRoot.OpenSubKey("ugmportalfile\\Shell\\Open\\Command", true);
//Microsoft.Win32.RegistryKey regKey;
regKey = Microsoft.Win32.Registry.ClassesRoot;
regKey.OpenSubKey(@"ugmportalfile\Shell\Open\Command");
regKey.SetValue("Default", @"%TPR%\start_manager.bat");
regKey.Close();

Solution

  • OpenSubKey does return a RegistryKey object, you are trying to modify a wrong key.

    RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot;
    RegistryKey subkey = regKey.OpenSubKey(@"ugmportalfile\Shell\Open\Command", true); // Could be also Microsoft.Win32.Registry.ClassesRoot..OpenSubKey(@"ugmportalfile\Shell\Open\Command", true);
    subkey.SetValue("Default", @"%TPR%\start_manager.bat");
    subkey.Close();
    

    You could also consider using code blocks 'cause of IDisposable interface.

    Edit: https://msdn.microsoft.com/en-us/library/xthy8s8d(v=vs.110).aspx