递归获取某一目录下所有子目录及子文件

传入参数为当前选择目录
private
List<DirectoryInfo> GetDirectoryInfos(DirectoryInfo info) { var infos = info.GetDirectories(); List<DirectoryInfo> infos1 = new List<DirectoryInfo>(); if (infos.Length == 0) { return null; } else { foreach(DirectoryInfo info1 in infos){ infos1.Add(info1); var infos2 = GetDirectoryInfos(info1); if (infos2 != null) { foreach (DirectoryInfo info2 in infos2) { infos1.Add(info2); } } } } return infos1; }

可以遍历List<DirectoryInfo>中的每一个DirectoryInfo,通过GetFiles方法获得所有子文件路径。

List<DirectoryInfo> infos = GetDirectoryInfos(infopath);
List<string> files = new List<string>();
foreach (DirectoryInfo info in infos)
{
     directory = info;
      foreach (FileInfo file in info.GetFiles())
      {
           files.add(file.FullName);
      }
}

 

posted @ 2021-05-11 16:07  zgffly  阅读(249)  评论(0编辑  收藏  举报