I decided last weekend to write my own RegEdit for Windows CE using the .NET CompactFramework. It turned out to be a fun little project, but I ran into a lot of trouble deleting Registry Keys. I used some sample code from a book to get started on this project, which was the root of the problem.
The main problem that I ran into was that when I tried to delete a Key, the code raised an UnauthorizedAccessException. Being fairly good at searching for information, I started searching the Internet in general, and then related newsgroups. That led me to some conflicting information:
1.       Statements that deleting Registry Keys is easy, and should just work
2.       A lot of information about security and permissions – none of which was valid for Windows CE and the .NET CompactFramework
After several hours of beating my head against the wall, it finally hit me that statement number 1 was correct. The caveat is that when opening a Key, it is important to close it when finished. Back to the sample code that I started with. The sample code assumed that the destructor in the RegistryKey class would close the key when it was destructed.  An, well, I trusted it.
Solution: I went back through all of my code and made sure that all of the opened RegistryKeys had a call to Close() when they were no longer needed.   But did that solve it completely? The answer is no. Keep in mind that other applications may have open Keys, so there may be Keys that cannot be deleted. I tested this using both C# and C, no difference.
How do you delete a Registry Key? The following is code to do it:
        static void Main(string[] args)
            RegistryKey RegKey = Registry.LocalMachine.OpenSubKey("Drivers\\Builtin", true);
This code uses DeleteSubKey() which will only delete the Key if there are no sub-values and sub-keys.
DeleteSubKeyTree() can also be used. DeleteSubKeyTree() will delete the Key and all sub-values and sub-keys.
Copyright © 2009 – Bruce Eitman
All Rights Reserved