[英]Getting Registry Key Delete Permission
I am trying to have my program determine if it has permission to delete a registry key in C#. 我试图让我的程序确定它是否有权删除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.
我一直在尝试这段代码,但实际上我没有注册表项的正确权限,因此返回true。
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
. 我要传递给此功能的注册表项是
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. 由于只为TrustedInstaller设置了“完全控制”权限,因此应该重新递归到子项
CLSID
并返回false。
Here are the permissions for HKEY_CLASSES_ROOT\\eHomeSchedulerService.TVThumbnailCache\\CLSID
from regedit: 这是来自regedit的
HKEY_CLASSES_ROOT\\eHomeSchedulerService.TVThumbnailCache\\CLSID
的权限:
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.
另外,我知道删除注册表项时只能使用try-catch块,但我想知道是否可以事先删除它。
I was able to do some digging on Google and I came up with this code which seems to do the trick: 我可以在Google上进行一些挖掘,然后想到了似乎可以解决问题的这段代码:
/// Checks if we have permission to delete a registry key
/// </summary>
/// <param name="key">Registry key</param>
/// <returns>True if we can delete it</returns>
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
{
System.Security.AccessControl.RegistrySecurity regSecurity = key.GetAccessControl();
foreach (System.Security.AccessControl.AuthorizationRule rule in regSecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount)))
{
if ((System.Security.AccessControl.RegistryRights.Delete & ((System.Security.AccessControl.RegistryAccessRule)(rule)).RegistryRights) != System.Security.AccessControl.RegistryRights.Delete)
{
return false;
}
}
return true;
}
}
catch (SecurityException)
{
return false;
}
}
Having read permissions allows you to open the key. 具有读取权限可让您打开密钥。 Try using:
尝试使用:
key.DeleteSubKey(subkey)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.