UnauthorizedAccessException while getting files

坚强是说给别人听的谎言 提交于 2019-12-18 09:17:27

问题


I am creating an application which finds duplication in files. When I search files like:

try
{
    string[] allFiles = Directory.GetFiles(
        directoryPath, "*.*", SearchOption.AllDirectories
    );

    for (int i = 0; i < allFiles.Length; i++)
    {
      //decisions
    }
}

catch (UnauthorizedAccessException ex)
{
    MessageBox.Show(ex.Message);
}

it says

Access to path 'C:\$Recycle.Bin....... ' is denied.

I want if a folder is not accessible then move to the next but execution of program stops at Directory.GetFiles method.


回答1:


Here's a class that will work:

public static class FileDirectorySearcher
{
    public static IEnumerable<string> Search(string searchPath, string searchPattern)
    {
        IEnumerable<string> files = GetFileSystemEntries(searchPath, searchPattern);

        foreach (string file in files)
        {
            yield return file;
        }

        IEnumerable<string> directories = GetDirectories(searchPath);

        foreach (string directory in directories)
        {
            files = Search(directory, searchPattern);

            foreach (string file in files)
            {
                yield return file;
            }
        }
    }

    private static IEnumerable<string> GetDirectories(string directory)
    {
        IEnumerable<string> subDirectories = null;
        try
        {
            subDirectories = Directory.EnumerateDirectories(directory, "*.*", SearchOption.TopDirectoryOnly);
        }
        catch (UnauthorizedAccessException)
        {
        }

        if (subDirectories != null)
        {
            foreach (string subDirectory in subDirectories)
            {
                yield return subDirectory;
            }
        }
    }

    private static IEnumerable<string> GetFileSystemEntries(string directory, string searchPattern)
    {
        IEnumerable<string> files = null;
        try
        {
            files = Directory.EnumerateFileSystemEntries(directory, searchPattern, SearchOption.TopDirectoryOnly);
        }
        catch (UnauthorizedAccessException)
        {
        }

        if (files != null)
        {
            foreach (string file in files)
            {
                yield return file;
            }
        }
    }
}

You can the use it like this:

IEnumerable<string> filesOrDirectories = FileDirectorySearcher.Search(@"C:\", "*.txt");

foreach (string fileOrDirectory in filesOrDirectories)
{
   // Do something here.
}

It's recursive, but the use of yield gives it a low memory footprint (under 10KB in my testing). If you want only files that match the pattern and not directories as well just replace EnumerateFileSystemEntries with EnumerateFiles.



来源:https://stackoverflow.com/questions/8548012/unauthorizedaccessexception-while-getting-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!