How to create different name for zip file irrespective of entry file name using GZIP c#

I’m working on zipping a file using GZip where zip file name different from that of entry name in it. I should also able to extract the zip file with that entry file name of original size. Below is code presently creating zip file but entry name is same as zip file name.

public static void GzipFile(string infile, string outfile) {         using (var outStream = new System.IO.Compression.GZipStream(File.OpenWrite(outfile),                                     System.IO.Compression.CompressionLevel.Fastest))         {             using (BinaryWriter binaryWriter = new BinaryWriter(outStream))             {                 byte[] buffer = new byte[100000];                 using (FileStream fileStream = new FileStream(infile, FileMode.Open))                 {                     int bytesRead = 0;                     do                     {                         bytesRead = fileStream.Read(buffer, 0, buffer.Length);                          if (bytesRead > 0)                         {                             binaryWriter.Write(buffer);                         }                     }                     while (bytesRead > 0);                 }                                     }         }                 } 
Add Comment
1 Answer(s)

GZipStream does not provide any methods to set the contents of the gzip header. If you need to do that, you will have to write your own header, then use DeflateStream to write the compressed data, compute the CRC-32 and keep track of the uncompressed length while compressing, and then when compression is complete, write the gzip trailer with the CRC-32 and length. You can find the format of the gzip header and trailer in RFC 1952.

However, I strongly doubt that you have any need to do that. Whatever will decompress the gzip stream you make will almost certainly ignore the name stored in the header. Library code will simply provide the uncompressed data. gunzip or unpigz will use the filename of what is being decompressed with the ".gz" stripped for the name of the result, not the name in the header. Unless you explicitly ask those programs to use the name in the header with a special option.

By the way, you keep using the term "zip", when this is about gzip, an entirely different format. Also a gzip stream does not have "entries", as it can only store one object. If you are just confused, and you’re really looking to make a zip file, then you need to use the ZipArchive class.

Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.