zip and unzip file in csharp

To zip a file:

main.cs
using System.IO.Compression;

void ZipFile(string inputFile, string outputFile)
{
    using (var inputStream = new FileStream(inputFile, FileMode.Open))
    {
        using (var outputStream = new FileStream(outputFile, FileMode.Create))
        {
            using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
            {
                inputStream.CopyTo(gZipStream);
            }
        }
    }
}
434 chars
16 lines

To unzip a file:

main.cs
using System.IO.Compression;

void UnzipFile(string inputFile, string outputFile)
{
    using (var inputStream = new FileStream(inputFile, FileMode.Open))
    {
        using (var outputStream = new FileStream(outputFile, FileMode.Create))
        {
            using (var gZipStream = new GZipStream(inputStream, CompressionMode.Decompress))
            {
                gZipStream.CopyTo(outputStream);
            }
        }
    }
}
438 chars
16 lines

Note: The GZipStream class provided by .NET framework is used to compress and decompress the file. The input file is read using a FileStream and output file is created using another FileStream. The CopyTo method is used to copy the compressed or decompressed data to the output stream.

gistlibby LogSnag