C# Denied Access Deleting Registry Value

送分小仙女□ 提交于 2019-12-25 05:07:28

问题


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 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";
    


来源:https://stackoverflow.com/questions/43816430/c-sharp-denied-access-deleting-registry-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!