简体   繁体   中英

How to check whether access permissions have changed for a directory in C#?

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.

选择了“安全性”选项卡的“属性”窗口

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM