获取注册表项删除权限

时间:2012-09-27 23:59:21

标签: c# windows permissions registry

我正在尝试让我的程序确定它是否有权删除C#中的注册表项。我一直在尝试这个代码,它返回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;
    }
}

我传递给此函数的注册表项是HKEY_CLASSES_ROOT\eHomeSchedulerService.TVThumbnailCache。它应该重新诅咒子键CLSID并返回false,因为仅为TrustedInstaller设置了完全控制权限。

以下是来自注册表的HKEY_CLASSES_ROOT\eHomeSchedulerService.TVThumbnailCache\CLSID权限: HKEY_CLASSES_ROOT\eHomeSchedulerService.TVThumbnailCache\CLSID permissions

我应该注意到我正在运行具有管理权限的代码。此外,我知道我可以在删除注册表项时使用try-catch块,但我想知道我是否可以事先删除它。

2 个答案:

答案 0 :(得分:0)

我能够在谷歌上进行一些挖掘,我想出了这个代码似乎可以解决这个问题:

    /// 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;
        }
    }

答案 1 :(得分:-1)

拥有读取权限允许您打开密钥。尝试使用:

key.DeleteSubKey(subkey)
相关问题