2009-01-13 118 views
19

我需要搜索一個驅動器(C:,D:等)的特定文件類型(擴展名如.xml,.csv,.xls)。如何執行遞歸搜索以循環所有目錄和內部目錄,並返回文件所在的完整路徑?或者我可以在哪裏獲得關於此的信息?遞歸文件搜索.net

VB.NET或C#

感謝

編輯〜我遇到像一些錯誤,無法訪問系統卷訪問被拒絕等有誰知道在哪裏可以看到實現文件中的一些smaple代碼搜索?我只需要搜索選定的驅動器並返回所有找到的文件的文件類型的完整路徑。

回答

20

這個怎麼樣?它避免了內置的遞歸搜索經常拋出的異常(即,您訪問被拒絕訪問單個文件夾,並且您的整個搜索都會死亡),並且被懶惰地評估(即它一找到它們就返回結果,而不是緩衝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); 
       } 
      } 
     } 
    } 
} 
+0

嗯...剛剛得到了一個downvote出藍色 - 照顧解釋爲什麼? – 2009-10-02 15:36:34

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

正是我想要的。簡單而有效。 – NMunro 2013-07-03 18:39:15

5

它看起來像recls庫 - 代表REC ursive LS - 現在有一個pure .NET implementation。我只是read about it in Dr Dobb's

將用作:

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