1.递归算法
using System;
using System.IO;
using System.Collections.Generic;
//暂存递归时文件夹绝对路径,防止异常时丢失
private string strTemp="";
//存储该文件内所有文件绝对路径泛型List
private List<string> AllFiles=new List<string>();
public void GetAllFiles(string strFolderPath)
{
GetCurrentFiles(strFolderPath);
GetChildFiles(strFolderPath);
}
//获取该文件夹的直接文件
private void GetCurrentFiles(string strFolderPath)
{
foreach(string temp in Directory.GetFiles(strFolderPath))
{
try
{
AllFiles.Add(temp);
}
catch
{
continue;
}
}
}
//递归获取所有子文件夹中的文件
private void GetChildFiles(string strFolderPath)
{
foreach(string temp in Directory.GetDirectories(strFolderPath))
{
this.strTemp=temp;
GetCurrentFiles(strTemp);
GetChildFiles(strTemp);
}
}
2.非递归算法
using System;
using System.IO;
using System.Collections.Generic;
public List<string> GetAllFiles(string strFolderPath)
{
List<string> AllFiles=new List<string>();
Queue<string> AllFolders=new Queue<string>();
AllFolders.EnQueue(strFolderPath);
while(AllFolders.Count>0)
{
string temp=AllFolders.DeQueue();
foreach(string temp1 in Directory.GetDirectories(strFolderPath))
{
AllFolder.EnQueue(temp);
}
foreach(string temp2 in Directory.GetFiles(strFolderPath))
{
try
{
AllFiles.Add(temp);
}
catch
{
continue;
}
}
}
return AllFiles;
}