Click to See Complete Forum and Search --> : [RESOLVED] RegistryKey method DeleteValue not working


MartyP
April 22nd, 2006, 12:08 PM
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:


//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/Tutorials/WinRegTutCSMCB.asp, but that didn't work for me either. (I created a string value as the code says using regedit.exe.)


// Delete the key value
RegistryKey delKey = Registry.LocalMachine.OpenSubKey("Software\\");
delKey.DeleteValue("MCBInc");


Any thoughts?

Many thanks,
MartyP

darwen
April 23rd, 2006, 06:50 PM
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.

MartyP
April 23rd, 2006, 08:03 PM
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

reg.DeleteSubKeyTree(@"Software\Microsoft\Windows\CurrentVersion\Run\App Name");

and

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.

MartyP
April 24th, 2006, 10:36 AM
I found out why I couldn't delete the value.

RegistryKey reg = Registry.LocalMachine.OpenSubKey(subKeyName);

should have been

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