本篇文章给大家分享的是有关C#中怎么拷贝整个文件夹及子目录,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
具体代码如下所示:
private void CopyDirectory( string srcPath, string desPath)
{
string folderName = srcdir.Substring(srcdir.LastIndexOf( "\\" )+1);
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;
}
以上就是C#中怎么拷贝整个文件夹及子目录,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。