I am trying to have my program determine if it has permission to delete a registry key in C#. I have been trying this code which is returning true when in fact I don’t have the right permissions for the registry key.
public static bool CanDeleteKey(RegistryKey key)
{
try
{
if (key.SubKeyCount > 0)
{
bool ret = false;
foreach (string subKey in key.GetSubKeyNames())
{
ret = CanDeleteKey(key.OpenSubKey(subKey));
if (!ret)
break;
}
return ret;
}
else
{
RegistryPermission r = new
RegistryPermission(RegistryPermissionAccess.AllAccess, key.ToString());
r.Demand();
return true;
}
}
catch (SecurityException)
{
return false;
}
}
The registry key that I am passing to this function is HKEY_CLASSES_ROOT\eHomeSchedulerService.TVThumbnailCache. It should be re-cursing to the sub key CLSID and returning false because the Full Control permission is only set for TrustedInstaller.
Here are the permissions for HKEY_CLASSES_ROOT\eHomeSchedulerService.TVThumbnailCache\CLSID from regedit:

I should note that I am running the code with Administrative privileges. Also, I know I can just use a try-catch block when I am deleting the registry key but I would like to know if I can delete it beforehand.
I was able to do some digging on Google and I came up with this code which seems to do the trick: