如何在所有驱动器的所有目录中搜索.txt文件? [英] How to search all directories in all drives for .txt files?

查看:48
本文介绍了如何在所有驱动器的所有目录中搜索.txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码搜索所有驱动器中的所有目录以搜索所有.txt文件:

I am using this code to search all directories in all drives to search for all .txt files:

public List<string> Search()
{
    var files = new List<string>();
    foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
    {
        files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
     }
     return files;
}

但是在运行时出现此错误:

but in running I am having this error:

如何解决?

谢谢.

推荐答案

这仅仅是一个权限问题.使用try/catch块.非特权代码无法访问磁盘上的某些文件夹,包括RecycleBin文件夹.

This is simply a permissions problem. Use a try/catch block. Some of the folders on your disk including RecycleBin folders are not accessible to unprivileged code.

public List<string> Search()
{
    var files = new List<string>();
    foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
    {
        try
        {
            files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
        }
        catch(Exception e)
        {
            Logger.Log(e.Message); // Log it and move on
        }
    }

    return files;
}

还请注意,将 Directory.GetFiles AllDirectories 选项一起使用存在一个固有的问题,即如果无法访问整个驱动器中的任何文件夹,则它将失败.您的结果中将不会得到该驱动器的任何文件.解决方案是进行手动递归.此SO问题a>.

Also note that using Directory.GetFiles with AllDirectories option has an inherent problem that it will fail if ANY of the folders in the entire drive is not accessible, and thus you'll not get any files for that drive in your results. The solution is to do manual recursion. An excellent example of that approach is available in this SO question.

这篇关于如何在所有驱动器的所有目录中搜索.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆