利用遞迴尋找某個目錄下的指定名稱所有檔案
阿新 • • 發佈:2019-02-06
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace FindHongliPdf { class Program { static void Main(string[] args) { FindPdf(); } /// <summary> /// 尋找匹配名稱的pdf /// </summary> public static void FindPdf() { string storagePath = @"\\10.10.129.77\巨潮下載測試\2017\20171130\新建資料夾\"; string path = @"C:\Users\qingping.li\Desktop\公司文件"; string pattern = ".*權益.*實施.*|.*分紅.*|.*派息.*|.*轉增.*|.*利潤分.*實施.*|.*紅.*分配.*"; //獲取所有檔案 DirectoryInfo Info = new DirectoryInfo(path); //獲得目錄下的所有資料夾(操作資料夾) DirectoryInfo[] dirInfoArray = Info.GetDirectories(); //開始複製 ErgodicDir(dirInfoArray, storagePath, pattern); } /// <summary> /// 遍歷資料夾 /// </summary> /// <param name="dirInfoArray"></param> public static void ErgodicDir(DirectoryInfo[] dirInfoArray, string storagePath, string pattern) { //遍歷資料夾 foreach (DirectoryInfo item in dirInfoArray) { //有單獨的檔案,就先複製檔案 CopyFile(item, storagePath, pattern); //如果有資料夾,繼續遍歷 if (item.GetDirectories().Length > 0) ErgodicDir(item.GetDirectories(), storagePath, pattern);//繼續掃描資料夾 else CopyFile(item, storagePath, pattern); //只有檔案 } } /// <summary> /// 複製檔案 /// </summary> /// <param name="item"></param> public static void CopyFile(DirectoryInfo item, string storagePath, string pattern) { if (item.GetFiles().Length > 0) { foreach (FileInfo file in item.GetFiles()) { if (file.Extension == ".pdf") { //匹配要掃描的檔名稱 if (Regex.IsMatch(file.Name, pattern)) if (!File.Exists(storagePath + file.Name)) File.Copy(file.FullName, storagePath + file.Name); } Console.WriteLine(file.FullName); } } } } }