C#拒绝访问删除注册表值 [英] C# Denied Access Deleting Registry Value
问题描述
当尝试创建一个 RunOnStartup 函数来检查天气或键是否存在时,如果存在,用户是否希望将其删除,我遇到了拒绝访问的问题.更具体地说是这个.
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.'
我的代码在这里.
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.
推荐答案
代码中有两个错误:
异常
UnauthorizedAccessException
- 'Cannot Write to the registry key' 表示您没有打开writable
RegistryKey> 模式.相反,您应该在尝试删除之前以写入模式打开它.确保将true
作为第二个参数传递,如下所示:
The exception
UnauthorizedAccessException
- 'Cannot Write to the registry key' indicates that the you didn't open theRegistryKey
inwritable
mode. Instead you should open it in write mode before trying to delete. Make sure you passtrue
as the second argument, like this:
RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\..", true);
reg.DeleteValue("MyApp");
最初您的 KeyName
和 if
条件检查在 HKEY_LOCAL_MACHINE
而您的插入/删除稍后参考 HKEY_CURRENT_USER
使用 Registry.CurrentUser
所以你应该让它们保持一致.
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";
这篇关于C#拒绝访问删除注册表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!