在.NET递归文件搜索 [英] Recursive File Search in .net

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

问题描述

我需要寻找一个驱动器(C:,D:等)的partuicular文件类型(扩展名状的.xml,.CSV,.xls的)。我如何preform递归搜索到循环中的所有目录和内部目录并返回该文件(S)的完整路径?或者我在哪里可以得到这些信息?

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#

感谢

编辑〜我遇到像一些错误,无法访问系统卷的访问被拒绝等,有谁知道在哪里我可以看到在实现文件搜索一些smaple code?我只是需要一个搜索所选驱动器并返回文件类型的完整路径找到的所有文件。

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的结果)。懒惰的行为,可以建立反应灵敏的用户界面等,也能够很好地处理LINQ(尤其是一()以()等)。

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天全站免登陆