C#递归法便利某个目录下的所有子文件夹和文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace CRApp
{
static class Program
{
static int Main(string[] args)
{
Console.Title = "文件列举工具 (www.prc.cx)";
Console.WriteLine("请输入路径:");
string filePath = Console.ReadLine();
List<string> fd = new List<string>();
int quantity = GetAllFileAndDirectory(filePath, fd,true,true,true); // 参数一:要枚举的起始目录,参数二:保存结果的列表,参数三:是否递归枚举,参数四:结果是否包含文件,参数五:结果是否包含文件夹。
Console.WriteLine($"目录或文件的总数是:{quantity}");
for (int i = 0; i < quantity; ++i)
{
Console.WriteLine("({0}) {1}", i + 1, fd[i]);
}
Console.ReadKey();
return (0);
}
public static int GetAllFileAndDirectory(string path,List<string> fileList, bool isRecursion = true, bool isContainFile=true,bool isContainFolder = true)
{
if (isContainFile==true)
{
string[] file = default(string[]);
try
{
file = Directory.GetFiles(path);
}
catch (Exception excep)
{
Console.WriteLine("错误: "+excep.Message);
return (0);
}
foreach (var f in file)
{
fileList.Add(f);
}
}
string[] folder =default(string[]);
try
{
folder = Directory.GetDirectories(path, "*");
}
catch (Exception excep)
{
Console.WriteLine("错误: "+excep.Message);
return (0);
}
foreach (var dir in folder)
{
if (isContainFolder==true)
{
fileList.Add(dir);
}
if (isRecursion==true)
{
GetAllFileAndDirectory(dir, fileList, isRecursion,isContainFile, isContainFolder);
}
}
return (fileList.Count());
}
}
}