简体   繁体   English

C#将文件从一个文件夹复制到另一个文件夹而不重复

[英]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.

相关问题 如何在C#中将文件从一个文件夹复制到另一个文件夹? - How to copy file from one folder to another in C#? 将所有pdf文件从一个路径复制到另一路径,而在c#中没有循环 - Copy all pdf files from one path to another without loop in c# 使用c#可靠地将文件从一台服务器复制到另一台 - Reliably copy files from one server to another using c# 在C#中将值从一个businesobject复制到另一个而没有循环 - Copy values from one businesobject to another without loop in c# 将文件从一个文件夹移动到另一个文件夹 - Moving files from one folder to another C# 尝试使用子文件夹C#将文件从一个文件夹移动到另一个文件夹 - Trying to move files from one folder to another with subfolders C# 删除文件,从另一个文件夹C#复制相同名称的文件 - Delete files, copy the same named files from another folder C# 如何使用C#从一个路径复制文件夹并将其粘贴到另一路径? - How to copy a folder from one one path and paste it to another path using C#? C#将最后一个文件从一个文件夹复制到另一个生成的文件夹 - C# copy last file from a folder into another generated folder C# 将文件从一个文件夹复制到另一个文件夹的真实时间 - C# true time for copying files from one folder to another folder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM