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?
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.
Elevating Visual Studio before opening to Run as administrator
is sufficent to edit registry from code.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With