C#检查并删除注册表项问题

C#检查并删除注册表项问题,c#,windows,registry,C#,Windows,Registry,我正在尝试检查(和删除)注册表项。代码: RegistryKey registryKey = Registry.CurrentUser.OpenSubKey ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); string codeBase = Assembly.GetExecutingAssembly().CodeBase;

我正在尝试检查(和删除)注册表项。代码:

 RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
                    ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

                string codeBase = Assembly.GetExecutingAssembly().CodeBase;


            if (registryKey != null)           //   <- !!!!!!!!! problem is here, i think
                {
                    registryKey.SetValue("MyApp", codeBase);
                }

                else
                {
                    registryKey.DeleteValue("MyApp");
                }
RegistryKey RegistryKey=Registry.CurrentUser.OpenSubKey
(“软件\\Microsoft\\Windows\\CurrentVersion\\Run”,true);
字符串codeBase=Assembly.getExecutionGassembly().codeBase;

if(registryKey!=null)/您在注册表中添加和删除的操作看起来不错,只是您的
if
-
else
条件有问题。如果要检查并删除注册表项,请执行以下操作:

string KeyName = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string valueName = "MyApp";
string codeBase = Assembly.GetExecutingAssembly().CodeBase;

if (Registry.GetValue(KeyName, valueName, null) != null)
{
     RegistryKey registryKey = Registry.CurrentUser
         .OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
     registryKey.DeleteValue(valueName);
}
Registry.GetValue(KeyName,valueName,null)
是执行null检查而不是执行
registryKey!=null
,因为registryKey只获取
。CurrentVersion\\Run
子项。相反,你应该为你的应用程序(例如MyApp)向下搜索实际的密钥


希望这有帮助

您在注册表中添加和删除的操作看起来不错,只是您的
if
-
else
条件有问题。如果要检查并删除注册表项,请执行以下操作:

string KeyName = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string valueName = "MyApp";
string codeBase = Assembly.GetExecutingAssembly().CodeBase;

if (Registry.GetValue(KeyName, valueName, null) != null)
{
     RegistryKey registryKey = Registry.CurrentUser
         .OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
     registryKey.DeleteValue(valueName);
}
Registry.GetValue(KeyName,valueName,null)
是执行null检查而不是执行
registryKey!=null
,因为registryKey只获取
。CurrentVersion\\Run
子项。相反,你应该为你的应用程序(例如MyApp)向下搜索实际的密钥


希望这有帮助

当您从代码使用注册表时,您将被移动到虚拟注册表的某个位置,以“Computer\HKEY\U LOCAL\U MACHINE\SOFTWARE\WOW6432Node”更详细地阅读检查和删除?然后您应该将
registryKey.DeleteValue(“MyApp”)
移动到
if
条件。由于打开子项
SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run
将永远不会执行
else
块,您是对的。非常感谢。当您从代码使用注册表时,您将被移动到虚拟注册表的某个位置,以“Computer\HKEY\U LOCAL\U MACHINE\SOFTWARE\WOW6432Node”更详细地阅读检查和删除?然后您应该将
registryKey.DeleteValue(“MyApp”)
移动到
if
条件。由于打开子项
SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run
将永远不会执行
else
块,您是对的。谢谢。