top of page

C# GZip Multiple Files


GZipStream C# Built In

An application I'm working on deals with loading in a group of files. I wanted to make it easier to import and export packages and so was looking at the compression options that C# has built in.


The System.IO.Compression namespace includes the GZipStream class that can be used to compress files and memory. The examples on MSDN show the straight forward way of compressing a single file, however in my case I wanted to do several files. Not wanting to use any 3rd party libraries, I came up with my own way of doing this.



GZipStream compresses a MemoryStream. The trick is to create a memory stream that contains the files to compress, and write it out in a single block. However the issue then becomes, how do you know what the files are and how big are they?


I blocked out the memory like this.

[FileNameLength 4bytes]

[FileName (FileNameLength bytes)]

[FileLength 8bytes]

[File (FileLength bytes)]

.. repeat



I was having issues at first when trying to write out the MemoryStream, and finally realized the issue was because the stream position was at the end of the memory stream. Be sure to stream.Position = 0 the stream before calling the CopyTo.


Then when Decompressing the package it is straight forward how to get the files


Calling the CopyTo on the GZipStream decompresses the files into the MemoryStream, and then it traverses through the memory parsing out each file.


And with that, you can package and unpackage multiple files! No Thirdparty libs required! This could be extended to include nested directories fairly easily. Just include the directories in the file name and when unpacking, create them. In my case I just need one level of files.


コメント


bottom of page