Compressing and decompressing folder and files using GZipStream in C#

In this article, learn how to compressing and decompressing folder and files using GZipStream in C#.


How to compressing and decompressing folder and files in C#:

The namespace System.IO.Compression supports GZip and Deflate algorithms. There are two methods that compress and decompress a byte stream which you can get from your file object. You can substitute GZipStream for DefaultStream in the methods below to use that algorithm.

1. How to Compress files and folders using GZipStream:

.
public static byte[] Compress(byte[] data)
{
    MemoryStream output = new MemoryStream();

    GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true);
    gzip.Write(data, 0, data.Length);
    gzip.Close();

    return output.ToArray();
}
.

2. How to Decompress files and folders using GZipStream:

.
public static byte[] Decompress(byte[] data)
{
    MemoryStream input = new MemoryStream();
    input.Write(data, 0, data.Length);
    input.Position = 0;

    GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);

    MemoryStream output = new MemoryStream();

    byte[] buff = new byte[64];
    int read = -1;

    read = gzip.Read(buff, 0, buff.Length);

    while (read > 0)
    {
        output.Write(buff, 0, read);
        read = gzip.Read(buff, 0, buff.Length);
    }

    gzip.Close();

    return output.ToArray();
}
.

– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Read Files List From Directory in C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo