简体   繁体   English

复制大量文件的最快方法

[英]Fastest way to copy a lot of files

What is the fastest way to copy a lot of files? 复制大量文件的最快方法是什么?

I wrote a program using this to copy files: 我用这个来编写程序来复制文件:

string datapath;
string savepath;

// Something like this to set the destination for datapath, and savepath:
using (System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
{
    if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        datapath = folderBrowserDialog.SelectedPath;
    }
}

// And then to copy the files:
IEnumerable<string> files = Directory.EnumerateFiles(datapath, "*", SearchOption.AllDirectories);

foreach (var file in files)
{
    File.Copy(file, savepath, true);
}

I copied about 3600 files (16,5 GB total) with this method and it took me 11m 30sec. 我用这种方法复制了大约3600个文件(总共16.5 GB),花了我11m 30秒。 When i copy the same files with WinExplorer, it takes about 9 minutes, using the same Directories and doing nothing else with the hdd in both tests. 当我使用WinExplorer复制相同的文件时,大约需要9分钟,使用相同的目录,并且在两个测试中都不使用hdd。

What are faster ways to handle this? 有什么更快的方法来处理这个问题?

// A simple source for demonstration purposes. Modify this path as necessary.
string[] files = Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
string newDir = @"C:\Users\Public\Pictures\Sample Pictures\Modified";
Directory.CreateDirectory(newDir);

// Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
Parallel.ForEach(files, (currentFile) => 
    {
        // The more computational work you do here, the greater 
        // the speedup compared to a sequential foreach loop.
        string filename = Path.GetFileName(currentFile);
        var bitmap = new Bitmap(currentFile);

        bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
        bitmap.Save(Path.Combine(newDir, filename));

        // Peek behind the scenes to see how work is parallelized.
        // But be aware: Thread contention for the Console slows down parallel loops!!!

        Console.WriteLine($"Processing {filename} on thread {Thread.CurrentThread.ManagedThreadId}");
        //close lambda expression and method invocation
    });

Paralel Foreach may help you. Paralel Foreach可以帮助你。 Source : https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop 资料来源: https//docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop

You can take a look at this library: https://quickio.net/ 你可以看看这个库: https//quickio.net/

The aim of this library is to provide the fastes way to copy files and retrieve file and folder structures by using win32 api calls. 这个库的目的是提供使用win32 api调用复制文件和检索文件和文件夹结构的简便方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM