为了防止小部分文件因为路径过长等原因阻断整个复制过程,特地添加了异常的不回报机制
using System;
using System.IO;
namespace YourNamespace.File
{
public static class FileOperator
{
/// <summary>
/// Copy directory to target path
/// </summary>
/// <param name="source">the directory you want to copy</param>
/// <param name="target">the target path</param>
/// <param name="throwException">whether throw exceptions when it meet issues, if false, it will skip the files which has problem</param>
public static void CopyDirectory(string source, string target, bool throwException = false)
{
DirectoryInfo sourceInfo = new DirectoryInfo(source);
FileSystemInfo[] children = sourceInfo.GetFileSystemInfos();
foreach (var child in children)
{
try
{
string targetName = Path.Combine(target, child.Name);
string containerDirectory = Path.GetDirectoryName(targetName);
if (child is DirectoryInfo)
{
CopyDirectory(child.FullName, targetName, throwException);
}
else
{
if (!Directory.Exists(containerDirectory))
Directory.CreateDirectory(containerDirectory);
(child as FileInfo).CopyTo(targetName);
}
}
catch (Exception exception)
{
if (throwException)
throw;
else
Console.WriteLine($"Copy file/folder failed {target}, here is the exception : {exception.ToString()}");
}
}
}
}
}