[英]Effective copying multiple files
我必須將很多文件從一個文件夾復制到另一個文件夾。 目前我這樣做:
string[] files = Directory.GetFiles(rootFolder, "*.xml");
foreach (string file in files)
{
string otherFile = Path.Combine(otherFolder, Path.GetFileName(file));
File.Copy(file, otherFile);
}
這是最有效的方式嗎? 似乎需要很長時間。
編輯:我真的問是否有更快的方法來進行批量復制,而不是復制單個文件,但我想答案是否定的。
我想不出比File.Copy更有效的方法,它直接進入操作系統。
另一方面,如果需要很長時間,我強烈建議顯示一個進度對話框 - 就像SHFileOperation為你做的那樣。 至少你的用戶會知道發生了什么。
您可以使用操作系統來移動文件。 這就像WinMerge這樣的工具。 單擊應用程序中的“復制”按鈕,它會彈出Windows進度框,就像您使用資源管理器排列副本一樣。 這個帖子描述了它。
我最近使用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
這似乎是一種快速且非常簡單的方法來更新進度條(使用sizeCopied)並在需要時取消文件傳輸(使用IsCancelled)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.