Search code examples
c#.net.net-framework-version

In .NET 8, I cannot successfully Read() the Stream obtained from the ZipFileEntry class


I am trying to copy the contents of a file opened with the ZipFile class into a byte array, but it doesn't seem to work.

When I try to get the 100KB entry "Data20240810" in a ZIP file using the code below, it seems to copy less than the actual data length.

using System;
using System.IO.Compression;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var zipfile = ZipFile.OpenRead("Test.zip");
            var zipfileEntry = zipfile.GetEntry("Data20240810");
            var fileStream = zipfileEntry?.Open();

            var rawData = new byte[102400];

            var readBytes = fileStream?.Read(rawData, 0, rawData.Length);

            Console.WriteLine($"Read size is {readBytes}");
            Console.WriteLine($"Rawdata size is {rawData.Length}");
        }
    }
}

In .NET Framework 4.8, the output below shows that the data is copied correctly into the array.

Read size is 102400
Rawdata size is 102400

In .NET 8, the output below shows that the data is only transferred halfway.

Read size is 8187
Rawdata size is 102400 

Did something change internally between .NET Framework and .NET?

I would be grateful if you could point me to some helpful documentation.


Solution

  • The issue was due to a breaking change since .NET6.

    https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams

    Read() on a DeflateStream in .NET 6 and later does not guarantee that the number of bytes requested will be read.

    According to the above documentation, it appears that a loop must be used to reproduce the previous behavior.