我需要搜索一个驱动器(C:d:等)用于partuicular文件类型(扩展像.XML,的.csv,.xls的)。如何大跳递归搜索循环中的所有目录和内部目录,并返回该文件(或多个)的完整路径?或者我在哪里可以得到这些信息?

VB.NET或C#

由于

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

有帮助吗?

解决方案

这个怎么样?它避免了通常由内置的递归搜索抛出的异常(即你得到拒绝访问到一个文件夹,你的整个搜索死亡),并懒洋洋地评估(即它返回尽快结果它发现了它们,而不是缓冲2000个结果)。懒惰的行为,可以建立响应用户界面等,也与LINQ(尤其是First()Take()等),效果很好。

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

其他提示

System.IO.Directory.GetFiles(@"c:\", "*.xml", SearchOption.AllDirectories);

它看起来像 recls 库 - 代表的录制的ursive的 LS - 现在有一个纯.NET实现。我只是读到它在多布博士的

将被用作:

using Recls;
using System;
static class Program { // formatted for vertical space
    static void Main() {
        foreach(IEntry e in FileSearcher.Search(@"c:\", "*.xml|*.csv|*.xls")) {
            Console.WriteLine(e.Path);
        }
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top