递归查找符合条件的文件,条件为后缀类型,并将结果存贮到队列中
public void TraverseFiles(string folderPath, string type, ConcurrentQueue<string> folderPathsQueue)
{
try
{
// 遍历当前文件夹下的所有文件符合条件的文件
foreach (string filePath in Directory.GetFiles(folderPath))
{
string[] tempArray = filePath.Split('.');
if (tempArray[tempArray.Length - 1] == type)
{
folderPathsQueue.Enqueue(filePath);
}
}
// 遍历文件夹下的所有子文件夹
foreach (string subFolderPath in Directory.GetDirectories(folderPath))
{
// 递归调用遍历文件夹方法
TraverseFiles(subFolderPath, type, folderPathsQueue);
}
}
catch (UnauthorizedAccessException)
{
// 如果无法访问文件夹,则在此处处理异常
}
}
递归查找符合条件的文件夹,这里判断的是文件夹下包含名字为AAA和BBB的文件夹并存入foldersPath队列
ConcurrentQueue<string> foldersPath = new ConcurrentQueue<string>();//文件夹路径队列
public void TraverseFolders(string folderPath)
{
// 判断文件夹是否存在
if (!Directory.Exists(folderPath))
{
return;
}
// 判断文件夹是否同时包含名称为"AAA"和"BBB"的两个文件夹
if (Directory.Exists(Path.Combine(folderPath, "AAA")) && Directory.Exists(Path.Combine(folderPath, "BBB")))
{
foldersPath.Enqueue(folderPath);
}
// 遍历子文件夹
string[] subFolders = Directory.GetDirectories(folderPath);
foreach (string subFolder in subFolders)
{
TraverseFolders(subFolder);
}
}