简体   繁体   English

如何删除注册表项?

[英]How to remove a registry key?

I'm trying to delete some registry Key but VS keeps telling me that I can't write in the registry key and I don't understand why : 我正在尝试删除一些注册表项,但是VS不断告诉我,我无法在注册表项中写入内容,而且我不明白为什么:

 public void refInstall()  
 {  
     RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Installer\Folders\MyApp");  
     foreach(string subKeyName in regKey.GetValueNames())  
     {  
         bool exist = Directory.Exists(subKeyName);  
         if (!exist)  
         {  
             regKey.DeleteSubKeyTree(subKeyName);  
             Console.WriteLine(subKeyName + ": N'EXISTE PAS");  
             }  
         }  
     }  
}

You don't have write access to HKLM. 您没有对HKLM的写权限。 You would need to run with elevated privileges in order for this to succeed. 您需要以提升的特权运行才能成功。

It's always been the case that rights to HKLM have been restricted to members of the administrators group. 通常,HKLM的权限仅限于管理员组的成员。 The thing that changed was in Vista when UAC was introduced and users habitually started running without admin rights. 发生变化的是在Vista中,当引入UAC并且用户习惯性地在没有管理员权限的情况下开始运行。

It may not be what you want to hear, but you need to get out of the habit of writing to this area of the registry, and find a different way to achieve your goals. 它可能不是您想听到的,但是您需要摆脱写注册表的这一区域的习惯,并找到实现目标的另一种方法。 The only time it is reasonable for a desktop app to expect write access to HKLM (or indeed Program Files directory) is at install time. 桌面应用程序期望对HKLM(或实际上是Program Files目录)的写访问的唯一时间是在安装时。

Once you fix your code as described by arx, you'll then have to tackle this issue. 按照arx的说明修复代码后,您将不得不解决此问题。

This has one obvious problem: 这有一个明显的问题:

You are iterating through registry values but trying to delete them as if they were keys . 您正在遍历注册表值,但是试图将它们当作来删除。

If you want to work with values use RegistryKey.DeleteValue . 如果要使用值,请使用RegistryKey.DeleteValue

If you want to work with keys use RegistryKey.GetSubKeyNames . 如果要使用键,请使用RegistryKey.GetSubKeyNames

Another problem: 另一个问题:

You are opening the registry key with read-only access. 您正在以只读访问权限打开注册表项。 You need (note the extra bool on the end): 您需要(请注意最后的多余布尔值):

RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Installer\Folders\MyApp", true);

(Deleted comments about Directory.Exists acting on the file system. This is deliberate as darky89 explains below.) (已删除有关Directory.Exists的注释,存在于文件系统上。这是有意的,如下darky89所述。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM