快速获取特定路径下的所有文件和目录

2023-12-29

我正在创建一个备份应用程序,其中 c# 扫描目录。在我使用类似的方法来获取目录中的所有文件和子文件之前:

DirectoryInfo di = new DirectoryInfo("A:\\");
var directories= di.GetFiles("*", SearchOption.AllDirectories);

foreach (FileInfo d in directories)
{
       //Add files to a list so that later they can be compared to see if each file
       // needs to be copid or not
}

The only problem with that is that sometimes a file could not be accessed and I get several errors. an example of an error that I get is:error

因此,我创建了一个递归方法来扫描当前目录中的所有文件。如果该目录中存在目录,则将再次调用该方法并传递该目录。这种方法的好处是,我可以将文件放在 try catch 块中,如果没有错误,我可以选择将这些文件添加到列表中,如果有错误,则可以选择将目录添加到另一个列表中。

try
{
    files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);               
}
catch
{
     //info of this folder was not able to get
     lstFilesErrors.Add(sDir(di));
     return;
}

所以这个方法效果很好,唯一的问题是当我扫描一个大目录时需要很多次。我怎样才能加快这个过程?我的实际方法是这样的,以防你需要。

private void startScan(DirectoryInfo di)
{
    //lstFilesErrors is a list of MyFile objects
    // I created that class because I wanted to store more specific information
    // about a file such as its comparePath name and other properties that I need 
    // in order to compare it with another list

    // lstFiles is a list of MyFile objects that store all the files
    // that are contained in path that I want to scan

    FileInfo[] files = null;
    DirectoryInfo[] directories = null;
    string searchPattern = "*.*";

    try
    {
        files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);               
    }
    catch
    {
        //info of this folder was not able to get
        lstFilesErrors.Add(sDir(di));
        return;
    }

    // if there are files in the directory then add those files to the list
    if (files != null)
    {
        foreach (FileInfo f in files)
        {
            lstFiles.Add(sFile(f));
        }
    }


    try
    {
        directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
    }
    catch
    {
        lstFilesErrors.Add(sDir(di));
        return;
    }

    // if that directory has more directories then add them to the list then 
    // execute this function
    if (directories != null)
        foreach (DirectoryInfo d in directories)
        {
            FileInfo[] subFiles = null;
            DirectoryInfo[] subDir = null;

            bool isThereAnError = false;

            try
            {
                subFiles = d.GetFiles();
                subDir = d.GetDirectories();

            }
            catch
            {
                isThereAnError = true;                                                
            }

            if (isThereAnError)
                lstFilesErrors.Add(sDir(d));
            else
            {
                lstFiles.Add(sDir(d));
                startScan(d);
            }


        }

}

如果我尝试用以下方法处理异常,就会出现问题:

DirectoryInfo di = new DirectoryInfo("A:\\");
FileInfo[] directories = null;
            try
            {
                directories = di.GetFiles("*", SearchOption.AllDirectories);

            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("There was an error with UnauthorizedAccessException");
            }
            catch
            {
                Console.WriteLine("There was antother error");
            }

如果发生异常,我就得不到任何文件。


这种方法要快得多。仅当目录中放置大量文件时才可以拨打电话。我的 A:\ 外部硬盘驱动器包含近 1 太比特,因此在处理大量文件时会产生很大的差异。

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo("A:\\");
    FullDirList(di, "*");
    Console.WriteLine("Done");
    Console.Read();
}

static List<FileInfo> files = new List<FileInfo>();  // List that will hold the files and subfiles in path
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
    // Console.WriteLine("Directory {0}", dir.FullName);
    // list the files
    try
    {
        foreach (FileInfo f in dir.GetFiles(searchPattern))
        {
            //Console.WriteLine("File {0}", f.FullName);
            files.Add(f);                    
        }
    }
    catch
    {
        Console.WriteLine("Directory {0}  \n could not be accessed!!!!", dir.FullName);                
        return;  // We alredy got an error trying to access dir so dont try to access it again
    }

    // process each directory
    // If I have been able to see the files in the directory I should also be able 
    // to look at its directories so I dont think I should place this in a try catch block
    foreach (DirectoryInfo d in dir.GetDirectories())
    {
        folders.Add(d);
        FullDirList(d, searchPattern);                    
    }

}

顺便说一下,多亏了你的评论,我才得到这个,吉姆·米歇尔

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

快速获取特定路径下的所有文件和目录 的相关文章

随机推荐

  • Django 自定义用户字段与 AbstractBaseUser 冲突

    我正在从现有数据库构建 Django 项目 该数据库正在被其他系统使用 因此我无法更改其架构 这是我当前的自定义用户模型 class Users AbstractBaseUser id user models IntegerField pr
  • 添加到 iPhone 主屏幕时,Web 应用程序感觉响应速度较慢

    当添加到 iPhone 上的主屏幕时 这个 Angular 2 应用程序的响应速度比在 Safari 中运行时的响应速度要慢 我通过将其添加到 index html 使其具有 Web 应用程序功能 如果你有几分钟时间 在 Github 页面
  • 在 Xcode 中,视图或窗口如何知道自身外部的 mouseDown?

    我想设计一个有点像弹出窗口的面板 当鼠标在它外面按下时 它可能会关闭或隐藏自己 但我不知道如何实现这一目标 我所知道的是一个视图可以处理 mouseDown mouseUp等等 但是当鼠标在其他地方按下时呢 我不知道如何捕捉这个事件 进一步
  • 如何使用 16GB 内存创建 Windows 虚拟机

    我对云服务完全陌生 使用 Windows Azure 我需要一个 Web 服务器和一个数据库服务器 每个服务器都有 16GB RAM 然而 超大的 Windows 虚拟机只有 14GB RAM 我如何为每台服务器添加 2GB RAM 或者我
  • rabbitmq 抛出 AmqpException: 找不到类 [B

    当我向 RabbitMQ 发送消息时 它会抛出 AmqpException for 循环 org springframework amqp rabbit listener exception ListenerExecutionFailedE
  • 通过 Git 将 Master 上未提交的更改放入新分支

    当我在分支时 如何将未提交的更改放入分支测试master 您还可以创建一个新分支并通过执行以下操作切换到它 git checkout b new branch git add 我一直使用这个 因为我总是忘记在开始编辑代码之前启动一个新分支
  • Alphavantage 和纳斯达克指数停止运行

    这个针对纳斯达克综合指数的 API 调用曾经有效 现在它只返回一个空的 JSON 没有错误消息 https www alphavantage co query function TIME SERIES MONTHLY symbol IXIC
  • webkit translateX 动画正在回滚到初始位置

    我正在尝试为移动 webkit 制作一个图片库 实际上足够快的唯一方法是使用硬件加速的translateX 我的问题是 div 在动画结束时收回其初始位置 我在左侧按钮上添加了 SlideGalLeft 类 到动画 div 您可以在此处的回
  • D3.js 使用嵌套数组从 tsv 迁移到 json

    我正在通过遵循教程并尝试阅读可用的示例来学习 d3 js 感谢迈克 在这个例子中 http bl ocks org mbostock 3884955 http bl ocks org mbostock 3884955 我无法理解如何从 ts
  • RxJava2 发布

    有什么区别 ObservableTransformer Observable merge it ofType x compose transformerherex it ofType y compose transformerherey a
  • FreeMarker 模板错误!在struts2中

    我在类中使用基于 Sturts 2 注释的验证 同时显示操作错误 我收到了这个奇怪的 FreeMarker 模板错误 这是我的实体类 Entity public class User implements Serializable priv
  • 如何使用 QEMU 模拟 vmx 功能?

    我读自here https www kernel org doc Documentation virtual kvm nested vmx txt必须通过向命令提供 vmx 选项来显式启用 QEMU 上的 vmx 功能支持 但问题是它似乎不
  • 使用 AllPermission 启用 Java SecurityManager

    我正在努力让自己熟悉SecurityManager但即使是这个简单的场景也失败了 当我从 IDE 内部或命令行运行以下命令时 我得到以下信息例外 https docs oracle com cd E19226 01 820 7699 abg
  • 无法使用 Python3 模块请求 POST 到 Grafana

    我正在尝试使用 Grafana 的后端 API 创建一个仪表板 我首先测试我的 API 令牌是否是使用 GET 设置的 并成功获得返回码 200 如下所示 然后 我尝试使用 POST 创建一个简单的仪表板 但我不断收到返回码 400 我很确
  • 表行划分

    好吧 我的应用程序有一个包含很多表格行的表格布局 但我如何在它们之间进行划分 例如 一个表格行 之后是一行 之后是另一个表格行 依此类推 有一些财产吗 Android 3 0 及更高版本中有此功能 在你的表格布局上 android divi
  • 单元测试方法中是否需要总结

    既然单元测试方法的命名使其目的更有意义 那么单元测试方法是否有必要添加摘要呢 Example
  • 如何将Python字典对象转换为numpy数组

    我有 python dict 对象 其键作为 datetime date 对象 值作为元组对象 gt gt gt data dict datetime date 2006 1 1 5 3 datetime date 2006 1 2 8 8
  • Slim + Twig - 如何在开发过程中关闭 Twig 缓存?

    这是我将其注入 Slim 容器中的树枝视图 Views and Templates https www slimframework com docs features templates html container view functi
  • PHP:包含和需要文件时抛出错误

    我尝试创建一个引导文件 但是每当我尝试在另一个文件中包含或需要它时 就会不断出现这样的错误 Warning require once folder file php function require once 无法打开流 没有这样的文件或目
  • 快速获取特定路径下的所有文件和目录

    我正在创建一个备份应用程序 其中 c 扫描目录 在我使用类似的方法来获取目录中的所有文件和子文件之前 DirectoryInfo di new DirectoryInfo A var directories di GetFiles Sear