1. 程式人生 > >c#遞迴遍歷指定資料夾內的所有檔案(包含子資料夾)

c#遞迴遍歷指定資料夾內的所有檔案(包含子資料夾)

c#程式碼:

 public class DirectoryAllFiles
    {
        static List<FileInformation> FileList = new List<FileInformation>();
        public static List<FileInformation> GetAllFiles(DirectoryInfo dir)
        {
            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                FileList.Add(new FileInformation{ FileName=fi.Name,FilePath=fi.FullName });
            }
            DirectoryInfo[] allDir= dir.GetDirectories();
            foreach (DirectoryInfo d in allDir)
            {
                GetAllFiles(d);
            }
            return FileList;
        }
    }

    public class FileInformation
    {
        public string FileName { get; set; }
        public string FilePath { get; set; }
    }

c#呼叫:
List<FileInformation> list = DirectoryAllFiles.GetAllFiles(new System.IO.DirectoryInfo(@"E:\電子資料"));
if (list.Where(t => t.FileName.ToLower().Contains("android")).Any()) Console.WriteLine("true");
foreach (var item in list)
{
   Console.WriteLine(string.Format("檔名:{0}---檔案目錄{1}",item.FileName,item.FilePath));
}