C#将文件从指定的目录复制到另一个目录

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;

}
}
}

转载于:https://www.cnblogs.com/leku_cc/archive/2013/02/07/2908905.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值