0

Possible Duplicate:
UnauthorizedAccessException cannot resolve Directory.GetFiles failure

This is the function im using to search the files:

public string SearchFor(string fileExtension, DirectoryInfo at)
    {
        string error = null;
        try
        {
            foreach (DirectoryInfo subDir in at.GetDirectories())
            {
                SearchFor(fileExtension, subDir);

                foreach (FileInfo f in at.GetFiles())
                {
                    // test f.name for a match with fileExtension
                    // if it matches...
                    //   yield return f.name;
                    if (f.Name == fileExtension)
                    {
                        return f.Name;
                    }
                    else
                    {
                        error = f.Name;
                    }
                }
            }
        }
        catch (UnauthorizedAccessException) { }
        return error;
    }

I know what to put for path when calling the function but what should i put for files ? How to use/call the function ? Im not sure what to put as for files .

Community
  • 1
  • 1
Daniel Lip
  • 3,867
  • 7
  • 58
  • 120
  • Similar question http://stackoverflow.com/questions/1393178/unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure – Amiram Korach Aug 23 '12 at 21:25
  • Amiram i tried the code in the link above you posted but im not sure in the function there in the solution what to put use as for the files that the function should get. Also someone coment there for the solution: This will fail to include all directories/files as the exception gets thrown on the first inaccessible file/directory and you never get any remaining accessible files after that point. Should i worry about this comment ? – Daniel Lip Aug 23 '12 at 23:14

2 Answers2

1

One option is to run the program as administrator. (right click and run-as-administrator)

Another option is to custom code your own directory search, something like:

public IEnumerator SearchFor(string fileExtension, DirectoryInfo at) {
  try {
    foreach (DirectoryInfo subDir in at.GetDirectories()) {
        SearchFor(fileExtension, subDir);

        foreach (FileInfo f in at.GetFiles()) {
            // test f.name for a match with fileExtension
            // if it matches...
            //   yield return f.name;
        }
    }
  } catch (UnauthroizedAccessException) { }
}
David Jeske
  • 2,306
  • 24
  • 29
0

If the windows account under which you are running the function does not have permission to change directory into a folder, you will get that exception if you try to access it from code. You can either handle it gracefully with a try / catch and continue the search, or you can try running under an account that has permissions to descend into that directory.

ryan0
  • 1,482
  • 16
  • 21