c#深拷贝文件夹示例

时间:2021-05-20

复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FileUtility
{
public class Program
{
public static void DeepCopy(DirectoryInfo source, DirectoryInfo target, params string[] excludePatterns)
{
if (target.FullName.Contains(source.FullName))
return;

// Go through the Directories and recursively call the DeepCopy Method for each one
foreach (DirectoryInfo dir in source.GetDirectories())
{
var dirName = dir.Name;
var shouldExclude = excludePatterns.Aggregate(false, (current, pattern) => current || Regex.Match(dirName, pattern).Success);

if (!shouldExclude)
DeepCopy(dir, target.CreateSubdirectory(dir.Name), excludePatterns);
}

// Go ahead and copy each file to the target directory
foreach (FileInfo file in source.GetFiles())
{
var fileName = file.Name;
var shouldExclude = excludePatterns.Aggregate(false,
(current, pattern) =>
current || Regex.Match(fileName, pattern).Success);

if (!shouldExclude)
file.CopyTo(Path.Combine(target.FullName, fileName));
}
}

static void Main(string[] args)
{
DeepCopy(new DirectoryInfo(@"d:/test/b"), new DirectoryInfo(@"d:/test/a"));
DeepCopy(new DirectoryInfo(@"d:/test/c"), new DirectoryInfo(@"d:/test/c/c.1"));
DeepCopy(new DirectoryInfo(@"d:/test/1/"), new DirectoryInfo(@"d:/test/2/"), new string[] { ".*\\.txt" });

Console.WriteLine("复制成功...");
Console.ReadKey();
}
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章