Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

registry

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?

like image 314
Pepe Avatar asked Jan 06 '16 17:01

Pepe


2 Answers

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.

like image 100
mwilczynski Avatar answered Oct 22 '22 08:10

mwilczynski


An alternative solution is to change the permissions on the registry key. Open the key using Regedit, right click and select 'Permissions'. Either add the profile that your application runs under (ie a service account) or select an existing group (ie Users) and grant them full access. This way you're not having to grant elevated privileges which is always a security concern.

like image 37
SteveC Avatar answered Oct 22 '22 08:10

SteveC