其实代码demo很简洁,只是逻辑有点绕,主要是要一层一层调用自己,要清楚当前是第几层调用,及递归调用时进的点和出的点在哪儿,一切就清晰明了了。
cs
/// <summary>
/// 删除指定目录下面的所有文件和文件夹
/// </summary>
/// <param name="path"></param>
/// <param name="level"></param>
/// <param name="isFirstCall"></param>
static void DeleteAllFilesAndFolders(string path,int level,bool isFirstCall)
{
level++;
Console.WriteLine($"Current Level:{level},Current Directory:{path}");
//删除当前目录下的所有文件
string[] files = Directory.GetFiles(path);
foreach (var file in files)
{
File.Delete(file);
}
//判断当前目录是否存在子目录
if(Directory.GetDirectories(path).Length != 0)
{
string[] dirs = Directory.GetDirectories(path);
for (int i = 0; i < dirs.Length; i++)
{
DeleteAllFilesAndFolders(dirs[i], level,false);
}
}
//删除当前目录,只保留传进来的根目录
if (!isFirstCall)
{
Directory.Delete(path);
Console.WriteLine($"已删除Level{level}目录:{path}");
}
}
/// <summary>
/// 将源路径下的所有文件和文件夹全部复制到目标文件夹中
/// </summary>
/// <param name="sourceDirectory"></param>
/// <param name="DestinationDirectory"></param>
/// <param name="level"></param>
static void CopyAllFilesAndFolders(string sourceDirectory,string DestinationDirectory,int level = 0)
{
level++;
Console.WriteLine($"Current Level: {level}");
Console.WriteLine($"Current Source Directory: {sourceDirectory}");
Console.WriteLine($"Current Destination Directory: {DestinationDirectory}");
//将源目录下的文件复制到目标目录下
string[] sourceFilePaths = Directory.GetFiles(sourceDirectory);
string sourceFileName = null;
foreach (string sourceFilePath in sourceFilePaths)
{
sourceFileName = Path.GetFileName(sourceFilePath);
File.Copy(sourceFilePath, DestinationDirectory + "\\"+ sourceFileName);
}
//从源头目录中获取其子目录
string[] dirs = Directory.GetDirectories(sourceDirectory);
string TargetDirectory = null;
if (dirs.Length !=0)
{
//在目标目录中创建子目录
for (int i = 0; i < dirs.Length; i++)
{
string[] dir_splited = dirs[i].Split('\\');
//TargetDirectory = dirs[i].Replace(sourceDirectory, DestinationDirectory);
TargetDirectory = DestinationDirectory + "\\" + dir_splited[dir_splited.Length - 1];
Directory.CreateDirectory(TargetDirectory);
CopyAllFilesAndFolders(dirs[i], TargetDirectory,level);
}
}
}
cs
private void CSV2List_Load(object sender, EventArgs e)
{
string sourceDirectory = @"D:\Test";
string targetDirectory = @"D:\Target";
//删除指定目录下的所有文件和文件夹
DeleteAllFilesAndFolders(targetDirectory, 0, true);
MessageBox.Show("Cleared");
CopyAllFilesAndFolders(sourceDirectory, targetDirectory,0);
MessageBox.Show("Copied");
}
代码执行的控制台输出如下:
运行程序,先清楚目标目录下的所有文件和文件夹,然后将源目录D:\Test下的所有文件和子目录都被复制到D:\Target目录下。