How to check if the application has access to a Directory?

.net, c#

Solution

I had used the following method to get it done:

public static bool HasWritePermissionOnDir(string path)
    {
        var writeAllow = false;
        var writeDeny = false;
        var accessControlList = Directory.GetAccessControl(path);
        if (accessControlList == null)
            return false;
        var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        if (accessRules == null)
            return false;

        foreach (FileSystemAccessRule rule in accessRules)
        {
            if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue;

            if (rule.AccessControlType == AccessControlType.Allow)
                writeAllow = true;
            else if (rule.AccessControlType == AccessControlType.Deny)
                writeDeny = true;
        }

        return writeAllow && !writeDeny;
    }

Please let me know if it helped you and if yes mark it too

Problem

In my application I need to check whether or not I have permissions to write to a folder. I use the following method: ``` public bool IsAvailable(string path) { bool hasPermissions = false; if (Directory.Exists(path)) { var permission = new FileIOPermission(FileIOPermissionAccess.Write, path); try { permission.Demand(); hasPermissions = true; } catch(SecurityException e) { hasPermissions = false; } } return hasPermissions; } ``` When I give it a path to a Folder that I know for certain no one has access to it (I've removed all permission for all users in the Security Tab of the Folder Properties), it doesn't throw any exception. It just continues along the try block. Any ideas why or how to do this check better? The AppDomain.PermissionSet Property related answers I found on other question had no succes. Thank you in advance.

Original source