复制大量文件的最快方法是什么?
我编写了一个程序来复制文件:
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 30sec。当我使用WinExplorer复制相同的文件时,大约需要9分钟,使用相同的目录,并且在两个测试中对HDD均不执行任何操作。
处理此问题的更快方法是什么?
答案 0 :(得分:4)
// 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
答案 1 :(得分:0)
您可以看一下这个库:https://quickio.net/
该库的目的是提供使用win32 api调用的复制文件以及检索文件和文件夹结构的快捷方式。