【发布时间】:2016-08-10 01:52:35
【问题描述】:
我正在使用这些代码来复制一个大文件:
const int CopyBufferSize = 64 * 1024;
string src = @"F:\Test\src\Setup.exe";
string dst = @"F:\Test\dst\Setup.exe";
public void CopyFile()
{
Stream input = File.OpenRead(src);
long length = input.Length;
byte[] buffer = new byte[CopyBufferSize];
Stopwatch swTotal = Stopwatch.StartNew();
Invoke((MethodInvoker)delegate
{
progressBar1.Maximum = (int)Math.Abs(length / CopyBufferSize) + 1;
});
using (Stream output = File.OpenWrite(dst))
{
int bytesRead = 1;
// This will finish silently if we couldn't read "length" bytes.
// An alternative would be to throw an exception
while (length > 0 && bytesRead > 0)
{
bytesRead = input.Read(buffer, 0, Math.Min(CopyBufferSize, buffer.Length));
output.Write(buffer, 0, bytesRead);
length -= bytesRead;
Invoke((MethodInvoker)delegate
{
progressBar1.Value++;
label1.Text = (100 * progressBar1.Value / progressBar1.Maximum).ToString() + " %";
label3.Text = ((int)swTotal.Elapsed.TotalSeconds).ToString() + " Seconds";
});
}
Invoke((MethodInvoker)delegate
{
progressBar1.Value = progressBar1.Maximum;
});
}
Invoke((MethodInvoker)delegate
{
swTotal.Stop();
Console.WriteLine("Total time: {0:N4} seconds.", swTotal.Elapsed.TotalSeconds);
label3.Text += ((int)swTotal.Elapsed.TotalSeconds - int.Parse(label3.Text.Replace(" Seconds",""))).ToString() + " Seconds";
});
}
文件大小约为 4 GB。
在最初的 7 秒内,它最多可以复制 400 MB,然后这个火热的速度就会平静下来。
会发生什么以及如何保持这个热速度甚至提高它?
还有一个问题: 复制文件后,windows 仍在处理目标文件(大约 10 秒)。
复制时间:116 秒
加时:10-15 秒甚至更多
如何消除或减少这个额外的时间?
【问题讨论】:
-
为什么不试试 XCopy
-
你为什么还要自己做呢?首先通过 CLR 运行每个字节会损失大部分性能。使用
File.Copy会显着加快速度。 -
@Toxantron File.Copy 需要 146 秒,但这种方法需要 116 秒。
-
老实说这毫无意义。
File.Copy是基于 Win32 API 构建的,其性能应该比您自己编写的同步副本至少高出 2 倍。例如,与此线程进行比较。 stackoverflow.com/questions/1246899/…
标签: c# file-copying