C#拒绝访问删除注册表值

时间:2017-05-06 03:29:51

标签: c# registry

当试图创建RunOnStartup函数来检查天气是否存在时,如果存在,那么用户是否希望删除它,我遇到了拒绝访问的问题。更具体地说。

System.UnauthorizedAccessException: 'Cannot write to the registry key.'

我的代码在这里。

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
            }
        }
    }

我可以创建密钥,只是不删除它,很奇怪。也许有一个我遗失的权限,我试图以管理模式运行,但同样的事情发生了。

1 个答案:

答案 0 :(得分:0)

代码中有两个错误:

  • 异常RegistryKey - “无法写入注册表项”表示您未在writable模式下打开true。相反,您应该在尝试删除之前以写入模式打开它。确保将RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\..", true); reg.DeleteValue("MyApp"); 作为第二个参数传递,如下所示:

    KeyName
  • 最初,您的ifHKEY_LOCAL_MACHINE条件会在HKEY_CURRENT_USER中进行检查,而您之后的插入/删除会使用Registry.CurrentUser引用string KeyName = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; ,所以您应该可能使它们保持一致。

    var alreadyRandom = false;
    
    function displayImage()
    {
      var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
      if(alreadyRandom)
      {
        // If the random for first time is done
        var rnd_no = img_name.indexOf(document.getElementById("imgHolder").getAttribute('src'));
        if(rnd_no === img_name.length-1)
        {
          // If the current image is the last one in array,
          // go back to the first one
          rnd_no = 0;
        }
        else
        {
          // Choose the next image in array
          rnd_no++;
        }
        document.getElementById("imgHolder").src = img_name[rnd_no];
      }
      else
      {
        var l = img_name.length;
        var rnd_no = Math.floor(l*Math.random());
        document.getElementById("imgHolder").src = img_name[rnd_no];
        alreadyRandom = true; // Tell the function not to random again
      }
      return img_name[rnd_no];
    }