Reputation: 36639
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.
Upvotes: 10
Views: 12004
Reputation: 1783
I recently implemented my file copies using filestreams in 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).
Upvotes: 1
Reputation: 11358
I can't think of a more efficient way than File.Copy, it goes directly to the OS.
On the other hand if it takes that long, I would strongly suggest to show a progress dialog - like SHFileOperation does it for you. At least your users will know what is happening.
Upvotes: 8
Reputation: 108236
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 thread describes it.
Upvotes: 1