Search code examples
c#file-permissions

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.

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?


Solution

  • 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