簡體   English   中英

復制大量文件的最快方法

[英]Fastest way to copy a lot of 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);
}

我用這種方法復制了大約3600個文件(總共16.5 GB),花了我11m 30秒。 當我使用WinExplorer復制相同的文件時,大約需要9分鍾,使用相同的目錄,並且在兩個測試中都不使用hdd。

有什么更快的方法來處理這個問題?

// 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可以幫助你。 資料來源: https//docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop

你可以看看這個庫: https//quickio.net/

這個庫的目的是提供使用win32 api調用復制文件和檢索文件和文件夾結構的簡便方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM