[英]C# to copy files from one folder to another without duplicates
Im trying to copy files from "source" folder to my "destination" folder, without duplicates.我试图将文件从“源”文件夹复制到我的“目标”文件夹,没有重复。 I cant use destination folder to compare as it will eventually get deleted from there.我无法使用目标文件夹进行比较,因为它最终会从那里删除。 I had gotten help here to make a batch file我在这里得到了帮助来制作批处理文件
Robocopy "source" "destination" "*chr.txt*" "*hdr.txt*" /M
that uses attribute to keep track of files copy before.使用属性来跟踪之前的文件副本。 However I need to do this in C# instead.但是,我需要在 C# 中执行此操作。 I know theres command to copy我知道要复制的命令
System.IO.File.Copy(sourceFile, destFile, true);
but not sure how to go about being specific on file name "*chr.txt" and taking care of duplicates.但不确定如何在文件名“*chr.txt”上具体化并处理重复项。
我需要在 C# 中执行此操作
Process.Start("robocopy", "source destination chr.txt hdr.txt /M");
Here is a method I created a while ago that has worked well for me (aside from the checking for duplicates part that I just added and haven't tested).这是我不久前创建的一种方法,对我来说效果很好(除了检查我刚刚添加但尚未测试的重复部分)。 Let me know if any parts of it do not work for what you need.如果它的任何部分无法满足您的需求,请告诉我。
private static void CopyDirectory(string from, string to)
{
var toFileNames = new DirectoryInfo(to)
.GetFiles()
.Select(f => f.Name)
.ToList();
var directory = new DirectoryInfo(from);
var files = directory.GetFiles();
foreach (var file in files)
if (!toFileNames.Contains(file.Name))
file.CopyTo(Path.Combine(to, file.Name));
var subDirectories = directory.GetDirectories();
foreach (var subDirectory in subDirectories)
{
var newDirectory = Directory.CreateDirectory(Path.Combine(to, subDirectory.Name));
CopyDirectory(subDirectory.FullName, newDirectory.FullName);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.