0

Following is the code that I have written,

var prevSecInfo = Directory.GetAccessControl(path);

if (Utilities.ShowChangePermissionsWindow(path)) {

    var currSecInfo = Directory.GetAccessControl(path);    

    if (currSecInfo != prevSecInfo)
        Utilities.ApplyPermissionsOnSubdirectories(path);
}

So, currently, I am getting the access control info before displaying the permissions window.

Next, I am displaying the permissions window which is actually the Security tab of the file/folder properties window. Changes can be made in permissions once it opens up.

Properties window with Security tab selected

But, in case no changes are made, I don't want to call my ApplyPermissionsOnSubdirectories() method. Hence, I am getting the access control info again in another variable and comparing the previous and the current info.

But, this isn't working. The comparison returns false even when no permissions are changed.

How can I check whether permissions have changed for the given path?

Pallab Pain
  • 134
  • 1
  • 11

2 Answers2

1

You cannot compare the contents of two reference type objects this way.

if (currSecInfo != prevSecInfo) will always return false, unless they both reference to the same object.

Unfortunately, DirectorySecurity type also does not provide Equals overriden method.

There is a StackOverflow article with some ready-made solutions for comparing permissions:
compare windows file (or folder) permissions

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
0

While working on the problem above, I found another solution which looks less complex and shorter is terms of code.

DirectorySecurity securityInfoBefore = Directory.GetAccessControl(path, AccessControlSections.Access);
string aclStrBefore = securityInfoBefore.GetSecurityDescriptorSddlForm(AccessControlSections.Access).ToString();

Here, path is the absolute path to the file/folder.

The aim to get the DirectorySecurity object before the permissions are changed and getting the SecurityDescriptorSddlForm as a string.

Now you can add your code to change the permissions. After the permissions are changed, add the following code,

DirectorySecurity securityInfoAfter = Directory.GetAccessControl(path, AccessControlSections.Access);
string aclStrAfter = securityInfoAfter.GetSecurityDescriptorSddlForm(AccessControlSections.Access).ToString();

The next step would be to compare the before and after strings.

if (aclStrBefore.Equals(aclStrAfter)) {
    // permissions have not changed
} else {
   // permissions have changed
}

This has helped me so far. Please feel free to add to my answer or correct it if required.

Pallab Pain
  • 134
  • 1
  • 11