[英]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. 尝试创建一个RunOnStartup Function来检查天气或是否存在某个键时,如果确实存在,用户是否希望将其删除,则遇到访问被拒绝的问题。 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.
可能缺少我的权限,我试图以管理模式运行,但发生了同样的事情。
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. 异常
UnauthorizedAccessException
'无法写入注册表项'表示您没有以writable
模式打开RegistryKey
。 Instead you should open it in write mode before trying to delete. 相反,您应在尝试删除之前以写入模式打开它。 Make sure you pass
true
as the second argument, like this: 确保将
true
作为第二个参数传递,如下所示:
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. 同样,最初,您的
KeyName
和if
条件检查在HKEY_LOCAL_MACHINE
而您的插入/删除以后则使用Registry.CurrentUser
引用HKEY_CURRENT_USER
因此您应该使它们保持一致。
string KeyName = @"HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.