有人会好心地解释使用分块流复制文件后如何使文件大小相同吗?我认为这是因为最后一个块的buffer
大小仍为 2048 ,因此它在末尾放置了空字节,但是我不确定如何调整最后一个读取的内容?>
原始大小:15.1 MB( 15,835,745 字节) 新大小::15.1 MB( 15,837,184 字节)
static FileStream incomingFile;
static void Main(string[] args)
{
incomingFile = new FileStream(
@"D:\temp\" + Guid.NewGuid().ToString() + ".png",
FileMode.Create,
FileAccess.Write);
FileCopy();
}
private static void FileCopy()
{
using (Stream source = File.OpenRead(@"D:\temp\test.png"))
{
byte[] buffer = new byte[2048];
var chunkCount = source.Length;
for (int i = 0; i < (chunkCount / 2048) + 1; i++)
{
source.Position = i * 2048;
source.Read(buffer, 0, 2048);
WriteFile(buffer);
}
incomingFile.Close();
}
}
private static void WriteFile(byte[] buffer)
{
incomingFile.Write(buffer, 0, buffer.Length);
}
答案 0 :(得分:0)
最后一次读取的 buffer
不必精确地包含2048
个字节(很可能是不完整)。想象一下,我们有一个5000
个字节的文件;在这种情况下,将读取 3 个块: 2 完成和 1 不完整
2048
2048
904 the last incomplete buffer
代码:
using (Stream source = File.OpenRead(@"D:\temp\test.png"))
{
byte[] buffer = new byte[2048];
var chunkCount = source.Length;
for (int i = 0; i < (chunkCount / 2048) + 1; i++)
{
source.Position = i * 2048;
// size - number of actually bytes read
int size = source.Read(buffer, 0, 2048);
// if we bytes to write, do it
if (size > 0)
WriteFile(buffer, size);
}
incomingFile.Close();
}
...
private static void WriteFile(byte[] buffer, int size = -1)
{
incomingFile.Write(buffer, 0, size < 0 ? buffer.Length : size);
}
在您的情况下,当您应写入15837184 == 7733 * 2048
个字节-7733
完成时,您写入15835745 == 7732 * 2048 + 609
个字节(7732
完整块) 块和最后一个不完整个609
字节之一