Reputation: 107
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?
Upvotes: 1
Views: 7346
Reputation: 27944
I think this will help:
File.Copy vs. Manual FileStream.Write For Copying File
It also explains why the copy function is slow.
Upvotes: 2
Reputation: 437336
The fastest (and most convenient) way to copy a file is probably File.Copy
. Is there a reason you are not using it?
Upvotes: 1
Reputation: 45083
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.
Upvotes: 2