1. 程式人生 > >遍歷目錄下的所有檔案

遍歷目錄下的所有檔案

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DownloadFile.Service
{
    class FileSearch
    {
        /// <summary>
        /// 獲取路徑下所有檔案以及子資料夾中檔案
        /// </summary>
        /// <param name="path">全路徑根目錄</param>

        public static List<FileAttrModel> GetFile(string path, List<FileAttrModel> listA)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] fil = dir.GetFiles();
            DirectoryInfo[] dii = dir.GetDirectories();
            foreach (FileInfo f in fil)
            {
                FileAttrModel fam = new FileAttrModel();
                fam.FileFullName = f.FullName;
                fam.FileName = f.Name;
                listA.Add(fam);
            }
            //獲取子資料夾內的檔案列表,遞迴遍歷
            foreach (DirectoryInfo d in dii)
            {
                GetFile(d.FullName, listA);
            }
            return listA;
        }
  
    }

    public class FileAttrModel
    {
        public string FileFullName { get; set; }
        public string FileName { get; set; }
    }
}