获取文件时出现UnauthorizedAccessException异常

本文关键字:UnauthorizedAccessException 异常 文件 获取 | 更新日期: 2023-09-27 18:18:22

我正在创建一个在文件中查找重复的应用程序。当我搜索如下文件时:

try
{
    string[] allFiles = Directory.GetFiles(
        directoryPath, "*.*", SearchOption.AllDirectories
    );
    for (int i = 0; i < allFiles.Length; i++)
    {
      //decisions
    }
}
catch (UnauthorizedAccessException ex)
{
    MessageBox.Show(ex.Message);
}

访问路径'C:'$Recycle.Bin.......'被拒绝。

我想如果一个文件夹是不可访问的,然后移动到下一个,但程序的执行停止在Directory.GetFiles方法。

获取文件时出现UnauthorizedAccessException异常

下面是一个可以工作的类:

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;
            }
        }
    }
}

你可以这样使用:

IEnumerable<string> filesOrDirectories = FileDirectorySearcher.Search(@"C:'", "*.txt");
foreach (string fileOrDirectory in filesOrDirectories)
{
   // Do something here.
}

它是递归的,但是使用yield使它占用的内存很少(在我的测试中不到10KB)。如果您只想要匹配模式的文件,而不是目录,只需将EnumerateFileSystemEntries替换为EnumerateFiles

相关文章:
  • 没有找到相关文章