开发者

Registry in .NET: DeleteSubKeyTree says the subkey does not exists, but hey, it does!

Trying to delete a subkey tree: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.hdr. .hdr subkey has one subkey, no values. So I use this code:

RegistryKey FileExts = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts");
RegistryKey faulty = FileExts.OpenSubKey(".hdr");
Debug.Assert (faulty != null && faulty.SubKeyCount != 0);
faulty.Close();
FileExts.DeleteSubKeyTree(".hdr");

And I get the ArgumentException with message "开发者_JS百科Cannot delete a subkey tree because the subkey does not exist."

WTF? I checked and asserted it did exist?

Status update

Seeking with Process Monitor, the subkey of ".hdr" gets a ACCESS DENIED error when running the code. I checked the autorizations, but they look fine?


Found a solution, which raises other another question...

After pointing the ACCESS DENIED error with Process Monitor, I just tried to delete subkeys individually:

RegistryKey hdr = FileExts.OpenSubKey(".hdr", true);
foreach (String key in hdr.GetSubKeyNames())
   hdr.DeleteSubKey(key);
hdr.Close();
FileExts.DeleteSubKeyTree(".hdr");

It worked fine, so it's not a permission problem!

For a reason I don't understand, DeleteSubKeyTree needed an empty tree to work.

An explanation, anyone?


I had the same issue but a different resolution. The DeleteSubKeyTree call raised ArgumentException saying the key didn't exist. It certainly does! I'm iterating over the existing key names and I am able to create a RegistryKey.

using (RegistryKey regClasses = Registry.ClassesRoot.OpenSubKey("CLSID", true))
{
    foreach (var class_guid in regClasses.GetSubKeyNames())
    {
        bool should_remove = false;
        using (RegistryKey productKey = regClasses.OpenSubKey(class_guid))
            should_remove = <some code here>
        if (should_remove)
            regClasses.DeleteSubKeyTree(class_guid);
    }
}

Then I realized I was debugging in user mode. When I ran as Admin it worked fine. Strange that the first OpenSubKey works in user mode, but when I open subkeys below this I correctly received Access Denied in user mode.


It looks to me like you might be confusing the concept of a SubKey with a the concept of a Name/Value pair (it's at the very least not clear from the original post whether you actually mean a subkey or a Name/Value pair). It's easy to confuse the two so here's the skinny on the Registry...

Folders in the registry correspond to subkeys, while Name/Value pairs are where values are stored. When you hold a reference to a subkey (i.e. folder) and you want to delete a Name/Value pair inside that subkey, you call subKey.DeleteValue(name).

using(subkey = Registry.CurrentUser.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
{
    subKey.DeleteValue(nameValuePairName);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜