1

I am trying to copy a lot of files using a loop and CopyTo method. The copy is very slow. abot 10 mb per minute! (in contrast to right click in mouse and copy).

Is there any alternatives to use, which are faster?

evilone
  • 22,410
  • 7
  • 80
  • 107
Question
  • 107
  • 1
  • 3

3 Answers3

2

I think this will help:

File.Copy vs. Manual FileStream.Write For Copying File

It also explains why the copy function is slow.

Community
  • 1
  • 1
Peter
  • 27,590
  • 8
  • 64
  • 84
2

Yes, use FileStream to buffer accordingly. As an example, something along the lines of this ought to give you an idea:

using (var inputStream = File.Open(path, FileMode.Read),
    outputStream = File.Open(path, FileMode.Create))
{
    var bufferRead = -1;
    var bufferLength = 4096;
    var buffer = new byte[bufferLength];

    while ((bufferRead = inputStream.Read(buffer, 0, bufferLength)) > 0)
    {
        outputStream.Write(buffer, 0, bufferRead);
    }
}

Adjust the bufferLength accordingly. You could potentially build things around this to enhance its overall speed, but tweaking slightly should still provide a significant enough improvement.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
1

The fastest (and most convenient) way to copy a file is probably File.Copy. Is there a reason you are not using it?

Jon
  • 428,835
  • 81
  • 738
  • 806