c# 复制文件夹中的所有文件夹与文件到另一个文件夹
2016-07-01 12:56
525 查看
#region 文件夹操作
/// <summary> //转载请注明来自 http://www.shang11.com
/// 复制文件夹中的所有文件夹与文件到另一个文件夹
/// </summary>
/// <param name="sourcePath">源文件夹</param>
/// <param name="destPath">目标文件夹</param>
public static void CopyFolder(string sourcePath,string destPath)
{
if (Directory.Exists(sourcePath))
{
if (!Directory.Exists(destPath))
{
//目标目录不存在则创建
try
{
Directory.CreateDirectory(destPath);
}
catch (Exception ex)
{
throw new Exception("创建目标目录失败:" + ex.Message);
}
}
//获得源文件下所有文件
List<string> files = new List<string>(Directory.GetFiles(sourcePath));
files.ForEach(c =>
{
string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
File.Copy(c, destFile,true);//覆盖模式
});
//获得源文件下所有目录文件
List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
folders.ForEach(c =>
{
string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
//采用递归的方法实现
CopyFolder(c, destDir);
});
}
else
{
throw new DirectoryNotFoundException("源目录不存在!");
}
}
/// <summary> //转载请注明来自 http://www.shang11.com
/// 复制文件夹中的所有文件夹与文件到另一个文件夹
/// </summary>
/// <param name="sourcePath">源文件夹</param>
/// <param name="destPath">目标文件夹</param>
public static void CopyFolder(string sourcePath,string destPath)
{
if (Directory.Exists(sourcePath))
{
if (!Directory.Exists(destPath))
{
//目标目录不存在则创建
try
{
Directory.CreateDirectory(destPath);
}
catch (Exception ex)
{
throw new Exception("创建目标目录失败:" + ex.Message);
}
}
//获得源文件下所有文件
List<string> files = new List<string>(Directory.GetFiles(sourcePath));
files.ForEach(c =>
{
string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
File.Copy(c, destFile,true);//覆盖模式
});
//获得源文件下所有目录文件
List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
folders.ForEach(c =>
{
string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
//采用递归的方法实现
CopyFolder(c, destDir);
});
}
else
{
throw new DirectoryNotFoundException("源目录不存在!");
}
}
相关文章推荐
- c#调用COM组件
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#实现给图片加水印的方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#中的delegate委托类型基本学习教程
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- 举例讲解C#中自动实现的属性
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#比较二个数组并找出相同或不同元素的方法