Tuesday, June 11, 2013

Zip in .NET 4.5

I was trying to zip a file today in .NET 4.5 and after looking around on the internet for a bit, realized a lot of the code was for the beta of the 4.5 framework and not the final version.  There were some API changes between the two and so the process changed a bit.  Here is a sample of how to zip a file in .NET 4.5:
// create a zip file 
var zipFilePath = "c:\\myfile.zip");
 
using (var zipFile = new FileStream(zipFilePath, FileMode.CreateNew))
{
    using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Create, false))
    {
        var dbZip = archive.CreateEntry("log.txt", CompressionLevel.Optimal);
 
        using (var writer = new BinaryWriter(dbZip.Open()))
        {
            writer.Write(File.ReadAllBytes("c:\\log.txt")); // here is where we read the file into the zip
            writer.Close();
        }
    }
    zipFile.Close();
}