Recursive File Search in .net

后端 未结 3 500
醉酒成梦
醉酒成梦 2020-12-08 15:57

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 di

相关标签:
3条回答
  • 2020-12-08 16:14

    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);
                    }
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-08 16:25

    It looks like the recls library - stands for recursive ls - now has a pure .NET implementation. I just read about it in Dr Dobb's.

    Would be used as:

    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);
            }
        }
    
    0 讨论(0)
  • 2020-12-08 16:30
    System.IO.Directory.GetFiles(@"c:\", "*.xml", SearchOption.AllDirectories);
    
    0 讨论(0)
提交回复
热议问题