For some reason I always thought that you needed to add a third party library to make a zip file in C#, but apparently you can do it easily with an API that already exists in the framework.
ZipArchive
All you need to do is create a file and associate the file stream with the ZipArchive. You can add files to the archive either straight from disk, or by writing them in memory.
Note that you have to provide the ZipArchiveMode.Create if you’re making a new zip file, otherwise a System.IO.InvalidDataException will be thrown because the file doesn’t exist on disk.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a file | |
using (var f = File.Create(@"C:\Some\Path\File.zip")) | |
{ | |
// Create the ZipArchive | |
using (ZipArchive za = new ZipArchive(f, ZipArchiveMode.Create)) | |
{ | |
// Create an entry in the zip file. You can add a path to make a | |
// directory strucutre inside of the zip file | |
var ze = za.CreateEntry(@"Logs\Log.txt"); | |
using (var logStream = ze.Open()) | |
{ | |
// Write some data in to the log file | |
var log = new byte[] { 72, 69, 76, 76, 79, 44, 32, 87, 79, 82, 76, 68 }; | |
logStream.Write(log, 0, log.Length); | |
} | |
} | |
} | |
// closing all of the using statements writes to disk |