简体   繁体   English

用C#复制非常慢

[英]Copy in c# is very slow

I am trying to copy a lot of files using a loop and CopyTo method. 我正在尝试使用循环和CopyTo方法复制很多文件。 The copy is very slow. 复制非常慢。 abot 10 mb per minute! abot每分钟10 mb! (in contrast to right click in mouse and copy). (与鼠标右键和复制相反)。

Is there any alternatives to use, which are faster? 是否有其他替代方法可以使用呢?

I think this will help: 我认为这会有所帮助:

File.Copy vs. Manual FileStream.Write For Copying File File.Copy与手动FileStream.Write用于复制文件

It also explains why the copy function is slow. 它还说明了为什么复印功能很慢。

Yes, use FileStream to buffer accordingly. 是的,使用FileStream进行相应的缓冲。 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. 相应地调整bufferLength You could potentially build things around this to enhance its overall speed, but tweaking slightly should still provide a significant enough improvement. 您可能会在此基础上构建一些东西来提高其总体速度,但是稍作调整仍然应该可以提供足够的改进。

The fastest (and most convenient) way to copy a file is probably File.Copy . 复制文件最快(最方便)的方法可能是File.Copy Is there a reason you are not using it? 您没有使用它的原因吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM