简体   繁体   中英

Unauthorized Access Exception DirectoryInfo.GetFiles() method

I wrote a program (on Windows 7) that call the method DirectoryInfo.GetFiles() , and in the folder "documents and settings", I have the exception of UnauthorizedAccess.

I tried lots of solutions, like:

create a manifest with


    `<requestedExecutionLevel level="highestAvailable" uiAccess="false" />`

and also with this

    DirectorySecurity dSecurity = Directory.GetAccessControl(dir.FullName);
    dSecurity.AddAccessRule(new FileSystemAccessRule("Luca", FileSystemRights.FullControl, AccessControlType.Allow));
    
    Directory.SetAccessControl(dir.FullName, dSecurity);

What could be the issue?

First off, you should be using DirectoryInfo.EnumerateFiles(...) instead of GetFiles(...). EnumerateFiles(...) keeps you from having to get the entire list until you actually need to.

I ran into this issue a while back and found that I ended up needing to implement a replacement IEnumerable in order to be able to complete an enumeration over folders that I may only have selected access to.

You can see the result of my research in the following thread. DirectoryInfo.EnumerateFiles(...) causes UnauthorizedAccessException (and other exceptions)

Just a Quick Copy Paste because I just had the same Problem. Adjust the Code to your needs (because I calculate the the size, counting all files and "save" all the Files I want to copy in a List). After you got all files in your List you can start copy them or what ever you wanna do with the Files:

private double CalculateSize(string sourcePath, Progress state, List<FileInfo> filesToCopy)
    {
        int _fileCount = 0;
        DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);

        FileInfo[] files = null;
        try
        {
            files = sourceDirectory.GetFiles();
        }
        catch(UnauthorizedAccessException ex)
        { 
            // DO SOME LOGGING-MAGIC IN HERE...
        }

        if (files != null)
        {
            foreach (FileInfo file in files)
            {
                fullSizeToCopy += file.Length;
                filesToCopy.Add(file);
                _fileCount++;
            }
        }

        DirectoryInfo[] directories = null;
        try
        {
            directories = sourceDirectory.GetDirectories();
        }
        catch(UnauthorizedAccessException ex)
        {
            // Do more logging Magic in here...
        }
        if (directories != null)
        foreach (DirectoryInfo direcotry in directories)
        {
            CalculateSize(direcotry.FullName, state, filesToCopy);
        }
        state.FileCount = _fileCount;

        return fullSizeToCopy;
    }

Your best bet might be to put a try/catch block around the call and ignore any directories you don't have access to. Maybe not the best solution, but it would at least make your method get all the directories you do have access to. Something like this:

try
{
    directory.GetFiles();
}
catch (UnauthorizedAccessException)
{
    string logMsg = string.Format("Unable to access directory {0}", directory.FullName);
    //Handle any desired logging here
}

Just like blow, use EnumerateDirectories rather than DirectoryInfo.getfiles

private void ScanEmptyDirs(string dir, ref int cnt, CancellationToken token)
    {
        if (String.IsNullOrEmpty(dir))
        {
            throw new ArgumentException("Starting directory is a null reference or an empty string: dir");
        }
        try
        {
            foreach (var d in Directory.EnumerateDirectories(dir))
            {                  
                if (token.IsCancellationRequested)
                {
                    token.ThrowIfCancellationRequested();
                }
                ScanEmptyDirs(d, ref cnt, token);
            }
            EmptyJudge(dir, ref cnt);
        }
        catch (UnauthorizedAccessException) { }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM