开发者

How to remove a registry key?

开发者 https://www.devze.com 2023-02-15 20:57 出处:网络
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 :

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 :

 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开发者_StackOverflow(subKeyName);  
             Console.WriteLine(subKeyName + ": N'EXISTE PAS");  
             }  
         }  
     }  
}


You don't have write access to 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. The thing that changed was in Vista when UAC was introduced and users habitually started running without admin rights.

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.

Once you fix your code as described by arx, you'll then have to tackle this issue.


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.

If you want to work with keys use 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消