2012-09-27 112 views
1

我想让我的程序确定它是否有权删除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块,但我想知道是否可以事先删除它。

+1

你还是应该写的'try' /'抓'块。理论上,其他系统可能会更改权限,或者在您的支票与实际发生的删除之间添加一个新的子密钥给您检查的密钥。 –

回答

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

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

key.DeleteSubKey(subkey) 
+0

我想查看是否只通过删除密钥就可以删除权限。 – ub3rst4r