【发布时间】:2017-03-03 11:31:35
【问题描述】:
我在服务器 A 中有一个 1GB,我必须使用 Read() 方法将它放到本地。它被拆分成包(16517 包)。每个包为 65536 字节,包含 header。
目前,我使用BinaryWriter 将每个包直接写入文件。但我花了 5 多分钟(323642 毫秒)。
我尝试将一些包加入到 10MB 的 byte[] 中,但这并没有减少时间(317397 毫秒)。
将byte[] 写入二进制文件的最佳方式是什么?
更新
const ulong Memory_10MB = 10485760; // 10MB
do {
byte[] packetData = Read(&totalSize, /*Other parameters*/ ,&hasFollowing);
if (package == null) {
// Process error
return;
}
dataSize += (ulong)packetData.Length;
if (dataSize >= Memory_10MB)
{
if (binaryWriter == null)
{
path = Path.GetTempFileName();
fileStream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
binaryWriter = new BinaryWriter(fileStream);
if (responseData.Length > 5)
{
binaryWriter.Write(responseData.Skip(5).ToArray());
}
}
binaryWriter.Write(packetData);
}
else
{
responseData = Utilities.ConcatArrays(responseData, packetData);
}
} while (dataSize < totalSize);
// Process after got data
【问题讨论】:
-
如果您只是使用 Windows 资源管理器复制文件,需要多长时间?不管它是什么,我都不指望你能改进很多。
-
你是怎么写数据的?请发布您的代码。
-
首先,我的输出文件在
Temp文件夹下。我将它复制到另一个驱动器中。大约需要 3 秒 -
给定这段代码,你如何区分
Read()和Write()的时间?我怀疑 Read() 负责这 5 分钟的大部分时间。 -
responseData.Skip(5).ToArray() 分配一个大数组。写(responseData,5,responsedata.Length-5)不是更好吗? (假设 responseData 是一个字节数组)。编辑:我现在才注意到它不是循环的一部分,所以性能增益很低。
标签: c# arrays binaryfiles binarywriter