C# 有效复制多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/222470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Effective copying multiple files
提问by Grzenio
I have to copy quite a lot of files from one folder to another. Currently I am doing it in this way:
我必须将相当多的文件从一个文件夹复制到另一个文件夹。目前我是这样做的:
string[] files = Directory.GetFiles(rootFolder, "*.xml");
foreach (string file in files)
{
string otherFile = Path.Combine(otherFolder, Path.GetFileName(file));
File.Copy(file, otherFile);
}
Is that the most efficient way? Seems to take ages.
这是最有效的方法吗?似乎需要很长时间。
EDIT: I am really asking if there is a faster way to do a batch copy, instead of copying individual files, but I guess the answer is no.
编辑:我真的在问是否有更快的方法来进行批量复制,而不是复制单个文件,但我想答案是否定的。
采纳答案by liggett78
I can't think of a more efficient way than File.Copy, it goes directly to the OS.
我想不出比 File.Copy 更有效的方法,它直接进入操作系统。
On the other hand if it takes that long, I would strongly suggest to show a progress dialog - like SHFileOperationdoes it for you. At least your users will know what is happening.
另一方面,如果需要那么长时间,我强烈建议显示一个进度对话框 - 就像SHFileOperation为你做的那样。至少你的用户会知道发生了什么。
回答by Michael Haren
You could use the operating system to move the files. This is what tools like WinMerge do. You click the "copy" button in your app and it pops up the Windows progress box as if you had used Explorer to arrange the copy. This threaddescribes it.
您可以使用操作系统来移动文件。这就是像 WinMerge 这样的工具所做的。您单击应用程序中的“复制”按钮,它会弹出 Windows 进度框,就像您使用资源管理器排列副本一样。这个线程描述了它。
回答by JFV
I recently implemented my file copies using filestreams in VB .NET:
我最近在 VB .NET 中使用文件流实现了我的文件副本:
fsSource = New FileStream(backupPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 1024, FileOptions.WriteThrough)
fsDest = New FileStream(restorationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, FileOptions.WriteThrough)
TransferData(fsSource, fsDest, 1048576)
Private Sub TransferData(ByVal FromStream As IO.Stream, ByVal ToStream As IO.Stream, ByVal BufferSize As Integer)
Dim buffer(BufferSize - 1) As Byte
Do While IsCancelled = False 'Do While True
Dim bytesRead As Integer = FromStream.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then Exit Do
ToStream.Write(buffer, 0, bytesRead)
sizeCopied += bytesRead
Loop
End Sub
It seems fast and a very easy way to update the progressbar (with sizeCopied) and cancel the file transfer if needed (with IsCancelled).
更新进度条(使用 sizeCopied)并在需要时取消文件传输(使用 IsCancelled)似乎是一种快速且非常简单的方法。