C#复制源文件夹到目标文件夹
程序员文章站
2024-03-09 10:04:47
...
static void CopyFolder(string srcPath,string tarPath)
{
string strFolderName = srcPath.Substring(srcPath.LastIndexOf("\\")+1,srcPath.Length -srcPath.LasttIndexOf("\\")-1;
//获得文件名夹名
if(!Directory.Exists(tarPath+"\\"+strFolderName))
Directory.CreateDirectory(tarPath + "\\"+ strFolderName);//目标文件夹没此文件夹,则创建
string [] strFiles = Directory.GetFiles(srcPath,"",SearchOption.AllDirectories);//获得文件夹所有文件
foreach(string strFilesElement in strFiles)
{
var strFileName = strFilesElement.Subsring(strFilesElement.LastIndexOf("\\")+1,strFilesElement.Length - strFilesElement.LastIndexOf("\\")-1);
//获得文件名
string tarAddress = tarPath+"\\"+strFileName;//目标路径
File.Copy(strFilesElement,tarAddress,true);//复制
}
DirectoryInfo dirInfo = new DirectoryInfo(srcPath);//获得其他文件,对每个文件夹做递归操作
DirectoryInfo[] dirPath = dirInfo.GetDirectories();
foreach(var dirPathElement in dirPath)
{
CopyFolder(srcPath + "\\" + dirPathElement.Name,tarPath + "\\" + dirPathElement.Name);
}
}