使用分块流复制文件会导致文件大小因上次读取而不同

Copy files with a chunked stream causes the files to be different sizes due to last read

有人可以解释一下我是如何在使用分块流复制文件后获得相同大小的文件的吗?我想这是因为最后一个块的 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);
        }

last 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 字节之一