.net 中的递归文件搜索 [英] Recursive File Search in .net

查看:16
本文介绍了.net 中的递归文件搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在驱动器(C:、D: 等)中搜索特定文件类型(扩展名为 .xml、.csv、.xls).如何执行递归搜索以循环所有目录和内部目录并返回文件所在位置的完整路径?或者我可以从哪里获得这方面的信息?

I need to search a drive (C:, D: etc) for a partuicular file type (extension like .xml, .csv, .xls). How do I preform a recursive search to loop all directories and inner directories and return the full path of where the file(s) are? or where can I get information on this?

VB.NET 或 C#

VB.NET or C#

谢谢

编辑~我遇到了一些错误,比如无法访问系统卷访问被拒绝等.有谁知道我在哪里可以看到一些关于实现文件搜索的简单代码?我只需要搜索选定的驱动器并返回找到的所有文件的文件类型的完整路径.

Edit ~ I am running into some errors like unable to access system volume access denied etc. Does anyone know where I can see some smaple code on implementing a file search? I just need to search a selected drive and return the full path of the file type for all the files found.

推荐答案

这个怎么样?它避免了内置递归搜索经常抛出的异常(即您被拒绝访问单个文件夹,并且您的整个搜索都失败了),并且被懒惰地评估(即它在找到结果后立即返回结果,而不是缓冲 2000 个结果).惰性行为使您可以构建响应式 UI 等,并且还可以很好地与 LINQ 配合使用(尤其是 First()Take() 等).

How about this? It avoids the exception often thrown by the in-built recursive search (i.e. you get access-denied to a single folder, and your whole search dies), and is lazily evaluated (i.e. it returns results as soon as it finds them, rather than buffering 2000 results). The lazy behaviour lets you build responsive UIs etc, and also works well with LINQ (especially First(), Take(), etc).

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
static class Program { // formatted for vertical space
    static void Main() {
        foreach (string match in Search("c:\", "*.xml")) {
            Console.WriteLine(match);
        }
    }
    static IEnumerable<string> Search(string root, string searchPattern) {
        Queue<string> dirs = new Queue<string>();
        dirs.Enqueue(root);
        while (dirs.Count > 0) {
            string dir = dirs.Dequeue();

            // files
            string[] paths = null;
            try {
                paths = Directory.GetFiles(dir, searchPattern);
            } catch { } // swallow

            if (paths != null && paths.Length > 0) {
                foreach (string file in paths) {
                    yield return file;
                }
            }

            // sub-directories
            paths = null;
            try {
                paths = Directory.GetDirectories(dir);
            } catch { } // swallow

            if (paths != null && paths.Length > 0) {
                foreach (string subDir in paths) {
                    dirs.Enqueue(subDir);
                }
            }
        }
    }
}

这篇关于.net 中的递归文件搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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