1. 程式人生 > >C#中遍歷指定資料夾下的檔案或子檔案

C#中遍歷指定資料夾下的檔案或子檔案

今天用到查詢給定路徑下的所有檔案,記錄一下:
1、引入IO名稱空間
using System.IO;
2、用到的主要方法:
DirectoryInfo folder = new DirectoryInfo(filePath);
DirectoryInfo.GetFiles():獲取目錄中所有的檔案(不包含子目錄),返回型別為FileInfo[]
DirectoryInfo.GetDirectories():獲取目錄中所有的子目錄(不包含檔案),返回型別為DirectoryInfo[]
DirectoryInfo.GetFileSystemInfos():獲取目錄下的檔案和目錄,返回值型別為FileSystemInfo[]
測試程式碼:

	 string filePath = @"C:\Users\Administrator\Desktop\FamilyTest";
        DirectoryInfo folder = new DirectoryInfo(filePath);
        FileInfo[] files = folder.GetFiles();
        foreach (FileInfo file in files)
        {
            string fileName = file.Name;
            listBox1.Items.Add(fileName);
        }

        DirectoryInfo[] direcs = folder.GetDirectories();
        foreach (DirectoryInfo dinfo in direcs)
        {
            string direcName = dinfo.Name;
            listBox2.Items.Add(direcName);
        }

        FileSystemInfo[] systeminfo = folder.GetFileSystemInfos();
        foreach (FileSystemInfo info in systeminfo)
        {
            string sysName = info.Name;
            listBox3.Items.Add(sysName);
        }

測試結果:
在這裡插入圖片描述