views:

1209

answers:

4

I confess I’m new to C#. I am struggling with creating a method to delete a registry key using .NET. The method takes one string parameter which contains the complete key to be removed. Here’s a sample of what I’m trying to do that doesn’t work (obviously):

namespace NameHere
{
    class Program
    {
        static void Main(string[] args)
        {
            RegistryKey hklm = Registry.LocalMachine;
            hklm = hklm.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\")
     string strKey=”Test123”;
string fullPath = hklm + "\\" + strKey;
            deleteRegKey(fullPath);  
        }

        static void deleteRegKey(string keyName)
        {

            Registry.LocalMachine.DeleteSubKey(keyName);

        }
    } 
}

I’ve tried a few other iterations and googled for solutions but have, so far, been unable to put the pieces together. Any help would be greatly appreciated. Also, any explanation for why my lame attempt doesn’t work to help clarrify my knowledge gap would be awesome.

+2  A: 

I believe you have too many \'s. Try this:

RegistryKey hklm = Registry.LocalMachine;
hklm = hklm.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\")
string strKey=”Test123”;
string fullPath = hklm + strKey;
deleteRegKey(fullPath);
Correl
A: 

Look here

zoidbeck
A: 

I think @Correl has it.

But one way to help you debug would be to use this form of DeleteSubkey:

public void DeleteSubKey(
    string subkey,
    bool throwOnMissingSubKey
)

instead of the one you call with only one argument, and pass true as the second argument. That way, if

...the specified subkey does not exist, then an exception is raised.

The exception you get would be an ArgumentException.

JeffH
+1  A: 

This routine should really be a one-liner, like:

Registry.LocalMachine.DeleteSubKey( @"SYSTEM\ControlSet...\etc..." );

You shouldn't need to open a RegistryKey object, because Registry.LocalMachine is kind of already open for you.

If you do need to open a RegistryKey object to do something else, be aware that RegistryKey implements IDisposable, so now that you've created an object, you're responsible for disposing of it no matter what. So, you have to surround your code with try { ... } and call Dispose() in the finally block. Fortunately, this can be coded in C# more elegantly using using:

using( RegistryKey key = Registry.LocalMachine.OpenSubKey(...) ) {
    ...
}
azheglov