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

时间:2019-01-11 09:59:38

标签: c# stream filestream

有人会好心地解释使用分块流复制文件后如何使文件大小相同吗?我认为这是因为最后一个块的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);
        }

1 个答案:

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