C#拷贝整个⽂件夹及⼦⽬录和其中⽂件的⽅法下⾯⼀段代码给⼤家介绍C#拷贝整个⽂件夹以及⼦⽬录和其中⽂件,具体代码如下所⽰:
private void CopyDirectory( string srcPath, string desPath)
{
string folderName = srcdir.Substring(srcdir.LastIndexOf( "\\" )+1);getsavefilename
string desfolderdir = desPath + "\\" + folderName;
if (desdir.LastIndexOf( "\\" ) == (desPath.Length - 1))
{
desfolderdir = desPath + folderName;
}
string [] filenames = Directory.GetFileSystemEntries(srcPath);
foreach ( string file in filenames)
{
if (Directory.Exists(file))
{
string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf( "\\" ) + 1);
if (!Directory.Exists(currentdir))
{
Directory.CreateDirectory(currentdir);
}
CopyDirectory(file, desfolderdir);
}
else
{
string srcfileName = file.Substring(file.LastIndexOf( "\\" )+1);
srcfileName = desfolderdir + "\\" + srcfileName;
if (!Directory.Exists(desfolderdir))
{
Directory.CreateDirectory(desfolderdir);
}
File.Copy(file, srcfileName);
}
}
}
ps:C# 拷贝指定⽂件夹下的所有⽂件及其⽂件夹到指定⽬录
要拷贝的⽂件及其⽂件夹结构
其中.lab⽂件不能覆盖
/// <summary>
/// 拷贝oldlab的⽂件到newlab下⾯
/// </summary>
/// <param name="sourcePath">lab⽂件所在⽬录(@"~\labs\oldlab")</param>
/// <param name="savePath">保存的⽬标⽬录(@"~\labs\newlab")</param>
/// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
public bool CopyOldLabFilesToNewLab(string sourcePath, string savePath)
{
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
#region //拷贝labs⽂件夹到savePath下
try
{
string[] labDirs = Directory.GetDirectories(sourcePath);//⽬录
string[] labFiles = Directory.GetFiles(sourcePath);//⽂件
if (labFiles.Length > 0)
{
for (int i = 0; i < labFiles.Length; i++)
{
if (Path.GetExtension(labFiles[i]) != ".lab")//排除.lab⽂件
{
File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]), true);
}
}
}
if (labDirs.Length > 0)
{
for (int j = 0; j < labDirs.Length; j++)
{
Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));
//递归调⽤
CopyOldLabFilesToNewLab(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]));      }
}
}
catch (Exception)
{
return false;
}
#endregion
return true;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。