c#深拷贝文件夹示例
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();
}
}
}