冰楓論壇

標題: [C#] 搜尋指定目錄下具特定關鍵字檔名與特定副檔名的檔案 [打印本頁]

作者: whitefox    時間: 2023-5-31 09:07
標題: [C#] 搜尋指定目錄下具特定關鍵字檔名與特定副檔名的檔案
這個例子會用到遞迴傳遞跟使用正則表達式來篩選關鍵字

例子開始前別忘先引入命名空間
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
複製代碼
此例子可以省略引入的是
System → 使用 try...cathc... 中使用 Exception 才會用到
System.Collections.Generic → 使用 List 來返回查詢結果,若使用 ObservableCollection 有同樣功能也不用引入此命名空間

Keyword給字串"*"就可搜尋指定副檔名的全部檔案
Extension給字串"*"就可以搜尋指定關鍵字的全部檔案
以上兩者都給"*"就是搜尋該目錄下全部檔案
  1. public static List<string> FindFile(string DirPath, string Keyword, string Extension)
  2. {
  3.     List<string> FoundList = new List<string>();

  4.     DirectoryInfo Dir = new DirectoryInfo(DirPath);
  5.     try
  6.     {
  7.         // 遞迴檢查子目錄
  8.         foreach (DirectoryInfo d in Dir.GetDirectories())
  9.         {
  10.             FoundList.AddRange(FindFile((Dir + d.ToString() + @"\"), Keyword, Extension));
  11.         }

  12.         foreach (FileInfo f in Dir.GetFiles("*." + Extension))
  13.         {
  14.             Regex regex = new Regex(Keyword);
  15.             Match match = regex.Match(f.ToString());

  16.             if (match.Success)
  17.             {
  18.                 FoundList.Add(Dir + f.ToString());
  19.             }
  20.         }
  21.     }
  22.     catch (Exception ex)
  23.     {
  24.         
  25.     }

  26.     return FoundList;
  27. }
複製代碼





歡迎光臨 冰楓論壇 (https://bingfong.com/) Powered by 冰楓