C# – access to the registry key is denied When i want update the value

cregistry

i want edit Registry key called "usbstor" value and this my code in update method

  try
        {
            string path = baseRegistryKey + "\\" + SubKey;
            Registry.SetValue(path, KeyName, KeyValue, RegistryValueKind.DWord);

            return true;
        }
        catch (Exception e)
        {
            // AAAAAAAAAAARGH, an error!
            ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
            return false;
        }

and path="HKEY_LOCAL_MACHINE\system\currentControlset\services\usbstor" keyname="start" When i run the code i'll get "Access to the registry key 'HKEY_LOCAL_MACHINE\system\currentControlset\services\usbstor' is denied"
what is probelm?

Best Answer

Executable

HKEY_LOCAL_MACHINE is always protected space in registry, so you need to either elavate privilliges to those of at least Power User or run your executable As Administrator (the one built from your solution, should be in ./bin folder) or disable UAC. Either way it will be troublesome inside Visual Studio as long as you don't have either way configured/set.

Note that if you try to use Run.. -> regedit you are also prompted by UAC, so that's not only restriction for your app but for access to registry per se.

Inside Visual Studio

Elevating Visual Studio before opening to Run as administrator is sufficent to edit registry from code.

Application manifest

For future usage you might want to create app.manifest and set your application to always require administrator privileges. Right click on your project in Solution Explorer, then: Add -> New Item... -> Application Manifest File. Inside your newly created application manifest, change the line:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

to line

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

From now on it will always prompt UAC if not run as administrator. If you run Visual Studio as not administrator, it will attempt to restart IDE as administrator, prompting to do so before proceeding.