c# 封装的文件夹操作类之复制文件夹

时间:2023-12-19 20:19:56

c#  封装的文件夹操作类之复制文件夹

一.复制文件夹原理:

1.递归遍历文件夹

2.复制文件

二.FolderHelper.cs

  /// <summary>
/// 文件夹操作类
/// </summary>
public static class FolderHelper
{
/// <summary>
/// 复制文件夹
/// </summary>
/// <param name="sourceFolderName">源文件夹目录</param>
/// <param name="destFolderName">目标文件夹目录</param>
public static void Copy(string sourceFolderName, string destFolderName)
{
Copy(sourceFolderName, destFolderName, false);
} /// <summary>
/// 复制文件夹
/// </summary>
/// <param name="sourceFolderName">源文件夹目录</param>
/// <param name="destFolderName">目标文件夹目录</param>
/// <param name="overwrite">允许覆盖文件</param>
public static void Copy(string sourceFolderName, string destFolderName, bool overwrite)
{
var sourceFilesPath = Directory.GetFileSystemEntries(sourceFolderName); for (int i = ; i < sourceFilesPath.Length; i++)
{
var sourceFilePath = sourceFilesPath[i];
var directoryName = Path.GetDirectoryName(sourceFilePath);
var forlders = directoryName.Split('\\');
var lastDirectory = forlders[forlders.Length - ];
var dest = Path.Combine(destFolderName, lastDirectory); if (File.Exists(sourceFilePath))
{
var sourceFileName = Path.GetFileName(sourceFilePath);
if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
File.Copy(sourceFilePath, Path.Combine(dest, sourceFileName), overwrite);
}
else
{
Copy(sourceFilePath, dest, overwrite);
}
}
}
}