using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace TEST
{
class FileHelper
{/// <summary>
/// 复制目录
/// </summary>
/// <param name="SourcePath">源路径</param>
/// <param name="TargetPath">目标路径</param>
/// <param name="Overwrite">是否覆盖</param>
public static bool CopyDirectory(string SourcePath, string TargetPath, bool Overwrite)
{
// 如果源目录不存在,则退出
if (!Directory.Exists(SourcePath))
{
return false;
}
// 检查目标目录是否以目录分割字符结束如果不是则添加
if (TargetPath[TargetPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
TargetPath += System.IO.Path.DirectorySeparatorChar;
}
try
{
// 如果目标路径不存在,则创建此文件夹
if (!Directory.Exists(TargetPath))
{
Directory.CreateDirectory(TargetPath);
}
}
catch (Exception ex)
{
string ErrInfo = ex.Message;
return false;
}
if (Directory.Exists(TargetPath))
{
// 遍历源路径的文件夹,获取文件名(带路径的)
foreach (string FileName in Directory.GetFiles(SourcePath))
{
try
{
//复制文件
File.Copy(FileName, Path.Combine(TargetPath, Path.GetFileName(FileName)), Overwrite);
}
catch (Exception ex)
{
string ErrInfo = ex.Message;
}
}
// 子文件夹的遍历
foreach (string SubPath in Directory.GetDirectories(SourcePath))
{
//复制文件
CopyDirectory(SubPath, Path.Combine(TargetPath, Path.GetFileName(SubPath)), Overwrite);
}
}
return true;
}
}
}