Search code examples
c#registry

C# Denied Access Deleting Registry Value


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.


Solution

  • Two errors in your code:

    • The exception UnauthorizedAccessException - 'Cannot Write to the registry key' indicates that the you didn't open the RegistryKey in writable mode. Instead you should open it in write mode before trying to delete. Make sure you pass true as the second argument, like this:

      RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\..", true);
      reg.DeleteValue("MyApp");
      
    • Also initially your KeyName and if condition check in HKEY_LOCAL_MACHINE whereas your insertion/deletion later refer to HKEY_CURRENT_USER using Registry.CurrentUser so you should probably make them consistent.

      string KeyName = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";