Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public static bool IsFileAuthorizedAccess(string path)
{
    //TODO
    bool retValue;
    try
    {
        retValue = !string.IsNullOrWhiteSpace(path) && File.Exists(path);
        DirectorySecurity obj = Directory.GetAccessControl(path);
        FileSecurity oqbj = File.GetAccessControl(path);
    }
    catch (UnauthorizedAccessException ex)
    {
        retValue = true;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retValue;
}

public static bool CanReadFile(string path)
{
    //TODO
    var readAllow = false;
    var readDeny = false;
    try
    {
        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.Read & rule.FileSystemRights) != FileSystemRights.Read) continue;

            if (rule.AccessControlType == AccessControlType.Allow)
                readAllow = true;
            else if (rule.AccessControlType == AccessControlType.Deny)
                readDeny = true;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
    return readAllow && !readDeny;
}
Posted
Updated 5-Mar-14 0:49am
v3
Comments
Maarten Kools 4-Mar-14 2:25am    
You didn't mention what your issue is...?
Member 10570161 4-Mar-14 2:30am    
I need to check whether user has authorized permission. And it must show whether file/folder is accessible or not. But its not showing when i click on particular folder
Maarten Kools 4-Mar-14 3:53am    
Seems to me this code should work fine. There's no mention of a click though, and what do you mean "it's not showing"?
Member 10570161 4-Mar-14 2:44am    
Do i need to add anything in UnauthorizedAccessException?
Member 10570161 5-Mar-14 6:50am    
. There is an issue i.e i cant create a file in C directory because access is not there. Am calling this CanRead function in another class and trying to add files to paths. But i couldnt create new file in C paths.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900