Wednesday, May 22, 2013

check if folder exists and can be read

using System.IO;
using System.Security.AccessControl;
...
bool dirExists = Directory.Exists(fileDir);
bool accessToDir = ReadAccess(fileDir);
if (dirExists && accessToDir)
    Console.Write("there is access");
    ...
public bool ReadAccess(string dir)
{
    bool allow = false;
    bool deny = false;
    DirectorySecurity dirSecurity = Directory.GetAccessControl(dir);
    if (dirSecurity == null)
        return false;
    AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true
            ,typeof(System.Security.Principal.SecurityIdentifier));
    if (rules == null)
        return false;
    foreach (FileSystemAccessRule rule in rules)
    {
        if ((FileSystemRights.Read & rule.FileSystemRights) == FileSystemRights.Read)
        {
            if (rule.AccessControlType == AccessControlType.Allow)
                allow = true;
            else if (rule.AccessControlType == AccessControlType.Deny)
                deny = true;
        }
    }
    return allow && !deny;
}

No comments:

Post a Comment