tags:

views:

932

answers:

3

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.

+1  A: 

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.

Michael Haren
+4  A: 

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.

liggett78
Didn't you know, things actually go faster when you add a progress bar. At least, that's what the user will tell you.
Kibbee
A: 

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).

JFV