问题
When attempting to create a RunOnStartup Function that checks weather or not a key exists and if it does, does the user want it deleted, I encounter the problem of Access Denied. More specifically this.
System.UnauthorizedAccessException: 'Cannot write to the registry key.'
My code for this here.
private static void RunOnStartup()
{
string KeyName = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string valueName = "MyApp";
if (Registry.GetValue(KeyName, valueName, null) == null)
{
RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
reg.SetValue("MyApp", Application.ExecutablePath.ToString());
MessageBox.Show("The Program will now start on startup", "Startup");
}
else
{
DialogResult dialogResult = MessageBox.Show("This Program can already run on Start up. Do you want it to no longer do so?", "Start Up", MessageBoxButtons.YesNoCancel);
if(dialogResult == DialogResult.Yes)
{
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run").DeleteValue("MyApp");
}
else if(dialogResult == DialogResult.No)
{
MessageBox.Show("The Program will continue to run on Startup", "Startup", MessageBoxButtons.OK);
}
else if(dialogResult == DialogResult.Cancel)
{
//Do Nothing
}
}
}
I can create the key, Just not delete it, quite strange. Perhaps there is a permission I'm missing, I attempted to run in administrative mode but the same thing happened.
回答1:
Two errors in your code:
The exception
UnauthorizedAccessException- 'Cannot Write to the registry key' indicates that the you didn't open theRegistryKeyinwritablemode. Instead you should open it in write mode before trying to delete. Make sure you passtrueas the second argument, like this:RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\..", true); reg.DeleteValue("MyApp");Also initially your
KeyNameandifcondition check inHKEY_LOCAL_MACHINEwhereas your insertion/deletion later refer toHKEY_CURRENT_USERusingRegistry.CurrentUserso you should probably make them consistent.string KeyName = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
来源:https://stackoverflow.com/questions/43816430/c-sharp-denied-access-deleting-registry-value