Mega Code Archive

 
Categories / C# Tutorial / Security
 

Use RemoveAccessRuleAll method removes all rules that match user and AccessControlType, ignoring rights and flags

using System; using System.Security.AccessControl; using System.Security.Principal; using System.Security; using Microsoft.Win32; public class Example {     public static void Main()     {         string user = Environment.UserDomainName + "\\" + Environment.UserName;         RegistrySecurity mSec = new RegistrySecurity();         RegistryAccessRule rule = new RegistryAccessRule(user,              RegistryRights.ReadKey | RegistryRights.WriteKey                 | RegistryRights.Delete,              InheritanceFlags.ContainerInherit,              PropagationFlags.None,              AccessControlType.Allow);         mSec.AddAccessRule(rule);         rule = new RegistryAccessRule(user,              RegistryRights.TakeOwnership,              AccessControlType.Allow);         mSec.RemoveAccessRuleAll(rule);         ShowSecurity(mSec);     }     private static void ShowSecurity(RegistrySecurity security)     {         foreach( RegistryAccessRule ar in              security.GetAccessRules(true, true, typeof(NTAccount)) )         {             Console.WriteLine("        User: {0}", ar.IdentityReference);             Console.WriteLine("        Type: {0}", ar.AccessControlType);             Console.WriteLine("      Rights: {0}", ar.RegistryRights);             Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);             Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);             Console.WriteLine("   Inherited? {0}", ar.IsInherited);         }     } }