9

I get an UnautorizedAccessException running this code:

string[] fileList = Directory.GetFiles(strDir, strExt);

The exception occurs in c:\users\username\appdata How can I check if I have access permission (to list and read files) ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442

3 Answers3

9

First of all, I would manually check the permissions and see what blocks you and what doesn't. I am using something like this to check for permissions (for copy file):

AuthorizationRuleCollection acl = fileSecurity.GetAccessRules(true, true,typeof(System.Security.Principal.SecurityIdentifier));
bool denyEdit = false;
for (int x = 0; x < acl.Count; x++)
{
    FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x];
    AccessControlType accessType = currentRule.AccessControlType;
    //Copy file cannot be executed for "List Folder/Read Data" and "Read extended attributes" denied permission
    if (accessType == AccessControlType.Deny && (currentRule.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory)
    {
        //we have deny copy - we can't copy the file
        denyEdit = true;
        break;
    }
... more checks 
}

Also, there are some strange cases where a certain right on the folder changes the right for the files regardless of their individual permissions (will see if I can find what it is).

Rox
  • 1,985
  • 12
  • 19
4

Check article on code project which is about the thing you need, the is class created for this : The purpose of this class is to provide a simple answer to a common question, "Do I have permission to Read or Write this file?".

A simple way to test individual access rights for a given file and user

Note: cannot post whole code over here because its too long.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
3

First, call Directory.GetFiles for root directory. Catch UnauthorizedAccessException - if none, you have full access.

If caught - call the function for each subdir recursively, catch the exception, if caught - add such dir to list.

Write a recursive function with external list for forbidden dirs

abatishchev
  • 98,240
  • 88
  • 296
  • 433