Issue with trying to use GZipStream in C# to decompress a large gz file

Zed Yang 0 Reputation points Microsoft Employee
2023-11-10T04:47:52.8966667+00:00

I'm trying to use GZipStream in C# to decompress a large gz file (compressed 2.5 GB -> decompressed 30 GB). Using the following code and the output file is always 50KB. I tried the same code on a much smaller gz file ~500MB and it worked fine. Wondering if there is any limitation to the GZipStream class. Below is my code, I got it from https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?view=net-7.0

    private static void DecompressFile()
    {
        using (FileStream compressedFileStream = File.Open(gzipFilePath, FileMode.Open))         
		using (FileStream outputFileStream = File.Create(destinationFilePath))         
		using (var decompressor = new GZipStream(compressedFileStream, CompressionMode.Decompress))         		   	
		{             
			decompressor.CopyTo(outputFileStream);         
		}
    }

    
    ```

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,187 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 32,966 Reputation points Microsoft Vendor
    2023-11-10T07:08:04.8666667+00:00

    Hi @Zed Yang ,

    Please put decompressor. CopyTo(outputFileStream); in curly brackets after the Using statement to prevent the stream from being closed prematurely.

           private static void DecompressFile()
            {
                using (FileStream compressedFileStream = File.Open(CompressedFileName, FileMode.Open))
                using (FileStream outputFileStream = File.Create(DecompressedFileName))
                using (GZipStream decompressor = new GZipStream(compressedFileStream, CompressionMode.Decompress))
                {
                    decompressor.CopyTo(outputFileStream);
                }
            }
    

    Also try to use the TryCatch statement to catch possible exceptions.

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.