2

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.

1
  • What OS are you trying this on? Commented May 14, 2009 at 20:52

3 Answers 3

2

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(...) ) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);  

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.