Tuesday, January 17, 2012

Zipping using System.IO.Compression

To use System.IO.Compression, you need to add a reference to WindowsBase.dll.
 
The following code snippet shows how to use some of the provided functionalities...
 

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
 
public static class ZipHelper
{
    public static void ZipFiles(string path, IEnumerable files, CompressionOption compressionLevel = CompressionOption.Normal)
    {
        using (FileStream fileStream = new FileStream(path, FileMode.Create))
        {
            ZipHelper.ZipFilesToStream(fileStream, files, compressionLevel);
        }
    }
 
    public static byte[] ZipFilesToByteArray(IEnumerable files, CompressionOption compressionLevel = CompressionOption.Normal)
    {
        byte[] zipBytes = default(byte[]);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            ZipHelper.ZipFilesToStream(memoryStream, files, compressionLevel);
            memoryStream.Flush();
            zipBytes = memoryStream.ToArray();
        }
 
        return zipBytes;
    }
 
    public static void Unzip(string zipPath, string baseFolder)
    {
        using (FileStream fileStream = new FileStream(zipPath, FileMode.Open))
        {
            ZipHelper.UnzipFilesFromStream(fileStream, baseFolder);
        }
    }
 
    public static void UnzipFromByteArray(byte[] zipData, string baseFolder)
    {
        using (MemoryStream memoryStream = new MemoryStream(zipData))
        {
            ZipHelper.UnzipFilesFromStream(memoryStream, baseFolder);
        }
    }

Read more: Codeproject
QR: Zip-using-System-IO-Compression

Posted via email from Jasper-Net