[RESOLVED] RegistryKey method DeleteValue not working
Hello,
Has any tried deleting values from a registry subkey using .NET? I'm having trouble using the DeleteValue() method, because it always throws an exception whenever I try to delete a value, even though I know the value exists and I'm logged in as an Administrator on Windows XP.
This code always gets a System.UnauthorizedAccessException, with a detail that it "Cannot write to the registry key." I've tried deleting values other than ones in "Software\Microsoft\Windows\CurrentVersion\Run\" but that didn't work either.
Also, I know how to do it in C++, and that works, but I can't get this to work in .NET.
Here is the code I've tried using:
Code:
//if the value name exists, delete it
string subKeyName = @"Software\Microsoft\Windows\CurrentVersion\Run\"; //subkey name
string valueName = @"App Name"; //name of the more specific key that will hold the value, "" means (Default)
try
{
RegistryKey reg = Registry.LocalMachine.OpenSubKey(subKeyName);
if (reg != null)
{
reg.DeleteValue(valueName);
reg.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
Also, I've tried this code snippet from http://www.c-sharpcorner.com/Tutoria...egTutCSMCB.asp, but that didn't work for me either. (I created a string value as the code says using regedit.exe.)
Code:
// Delete the key value
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software\\");
delKey.DeleteValue("MCBInc");
Any thoughts?
Many thanks,
MartyP
Re: RegistryKey method DeleteValue not working
Try the DeleteSubKeyTree method instead : if your key has sub-keys then DeleteKey won't work.
Also every opened RegistryKey class needs to have a Close() call made on it before attempting to delete the key - even its parent keys.
Darwen.
Re: RegistryKey method DeleteValue not working
Thanks for your reply. When I changed my code to call Close() on the RegistryKey before attempting to delete the key, I got the error "Cannot access a closed registry key."
Also, I tried both
Code:
reg.DeleteSubKeyTree(@"Software\Microsoft\Windows\CurrentVersion\Run\App Name");
and
Code:
Registry.LocalMachine.DeleteSubKeyTree(@"Software\Microsoft\Windows\CurrentVersion\Run\App Name");
and I get the error "Cannot delete a subkey tree because the subkey does not eixst."
That made sense to me anyway, because "App Name" is one of the value names in the "Run" subkey tree and a value name isn't a subkey.
Any more ideas? Thanks.
Re: RegistryKey method DeleteValue not working
I found out why I couldn't delete the value.
Code:
RegistryKey reg = Registry.LocalMachine.OpenSubKey(subKeyName);
should have been
Code:
RegistryKey reg = Registry.LocalMachine.OpenSubKey(subKeyName,true);
The second parameter says whether to open the subkey in write-mode. Without it, the key is opened in read-only mode.
Thanks anyway for your help!
MartyP