拷贝文件夹A内的所有内容到B内

时间:2021-06-13 21:37:08

实现: 将 F:/test2下的所有数据 拷贝到 F:/test1内去

步骤:1.先清除 test1下的所有内容

   2.拷贝前判断是否是文件夹:   是文件夹:创建文件夹,并递归拷贝函数

                  是文件:直接拷贝

    public static void CopyTest()
{
string sourceFolderName = "F:/test2";
string destFolderName = "F:/test1";

CopyFileToFile(sourceFolderName, destFolderName, true);
}

/// <summary>
/// 把 文件夹下的所有文件拷贝到指定文件夹
/// </summary>
public static void CopyFileToFile(string sourceFolderName, string destFolderName, bool overwrite)
{
if (Directory.Exists(destFolderName))
{
DelectDir(destFolderName);
}
CopySubFun(sourceFolderName, destFolderName, true);
}

public static void CopySubFun(string sourceFolderName, string destFolderName, bool overwrite)
{
if (!Directory.Exists(sourceFolderName))
{
return;
}
if (!Directory.Exists(destFolderName))
{
Directory.CreateDirectory(destFolderName);
}

string[] sourceFilesPath = Directory.GetFileSystemEntries(sourceFolderName);

for (int i = 0; i < sourceFilesPath.Length; i++)
{
string sourceFilePath = (sourceFilesPath[i]).Replace("\\", "/");
string[] forlders = sourceFilePath.Split('/');

if (File.Exists(sourceFilePath))//是文件,直接拷贝
{
string dest = destFolderName;
string sourceFileName = Path.GetFileName(sourceFilePath);
File.Copy(sourceFilePath, Path.Combine(dest, sourceFileName), overwrite);
}
else if (Directory.Exists(sourceFilePath))//是文件夹,拷贝文件夹;并递归
{
string lastDirectory = forlders[forlders.Length - 1];
string dest = Path.Combine(destFolderName, lastDirectory).Replace("\\", "/");

if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
CopySubFun(sourceFilePath, dest, overwrite);
}
}
}

public static void DelectDir(string srcPath)
{

DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
File.Delete(i.FullName); //删除指定文件
}
}

}