Question

I am writing a class library using C# and .NET 4 that interacts with the filesystem on a shared server over the network. I am trying to adjust some permissions on a folder and I am perfectly capable to add ACEs, but I am struggling to remove them.

This is the code I have so far:

//get ACEs for the working folder.
DirectorySecurity disec = m_diWork.GetAccessControl();

//find out if the account we want to remove is inherited from a parent folder.
bool bIsAccountInherited = disec.GetAccessRules(false, true, typeof(NTAccount)).Cast<AuthorizationRule>().Any(ar => ar.IdentityReference.Value.Equals(act.Value, StringComparison.CurrentCultureIgnoreCase));
if (bIsAccountInherited)
{
    //if so, remove inheritance of ACEs but preserve existing ones.
    disec.SetAccessRuleProtection(true, true);
}

//remove all access to this account.
disec.PurgeAccessRules(act);

//commit changes to working folder.
m_diWork.SetAccessControl(disec);

The variable act is of type NTAccount and refers to a domain user.

The code runs without exceptions or any apparent issues, and the permissions of the target folder are correctly changed to non-inheriting. However, no ACEs are removed at all.

I have tried several different combinations of method calls, also using RemoveAccessRuleAll(), to no avail. What am I doing wrong? Thanks.

Était-ce utile?

La solution

The problem lays in the fact that you are trying to remove inherited access rights what is not allowed. It happens because it is not enough to call SetAccessRuleProtection(true, true). The changes will take effect only when you call SetAccessControl afterwards. In other words you cannot remove inheritance of access rights and modify them in the one shot. It must be done in 2 stages i.e.:

  1. disec.SetAccessRuleProtection(true, true);
  2. m_diWork.SetAccessControl(disec);
  3. disec = m_diWork.GetAccessControl()
  4. disec.PurgeAccessRules(act);
  5. m_diWork.SetAccessControl(disec);

It is not obvious and it doesn't help that PurgeAccessRules doesn't inform about problems with removing access rights.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top