I'm very excited about this. First off, I hate third-party dependencies. I always try to accomplish everything with the platform I use, in this case the BCL. A friend of mine was asking me to write a blog article on System.IO.Packaging
and how to use types like GZipStream
. After suggesting SharpZipLib and DotNetZip, I became a rather curious rhino and did a quick Object Browser search in the .NET 4.5 base class library for the term zip
. Sure enough, my eyes did not deceive me and I immediately saw ZipArchive
! You will need to add a reference to System.IO.Compression.dll
to use these types.
Immediately I began to just experiment with the type. After I wrote my own code on how I figured it would be used, I checked Msdn and sure enough my code was virtually identical to the example code.
namespace ZipArchiveDemo { using System; using System.IO; using System.IO.Compression; using System.Linq; class Program { static void Main(string[] args) { const string path = @"c:\users\danderson\my documents\archive.zip"; using (FileStream fstream = new FileStream(path, FileMode.Create)) using (ZipArchive archive = new ZipArchive(fstream, ZipArchiveMode.Create)) { ZipArchiveEntry entry = archive.CreateEntry("test.txt"); using (StreamWriter writer = new StreamWriter(entry.Open())) { writer.WriteLine("I'm just a curious little rhino!"); } } if (!File.Exists(path)) { throw new System.IO.FileNotFoundException(String.Format("{0} was not found.", path)); } using (FileStream fstream = new FileStream(path, FileMode.Open)) using (ZipArchive archive = new ZipArchive(fstream, ZipArchiveMode.Read)) { ZipArchiveEntry entry = archive.Entries.FirstOrDefault(); using (StreamReader reader = new StreamReader(entry.Open())) { Console.WriteLine(entry.Name); Console.WriteLine(reader.ReadToEnd()); } } Console.ReadKey(); } } }
Pretty simple and not much else to it. The first two using blocks create the archive and then I just do a quick check if it was created, and throw an Exception otherwise. The last set opens the archive and grabs the first entry (since there's only one) and writes it to the standard output stream.
I have to hand it to the BCL team on this one. THANK YOU.
2 Comments
Leave a Comment
You must be logged in to post a comment.
Pingback: ZipFile class (System.IO.Compression.FileSystem) - Blog - danderson.io
Pingback: ZipFile class (System.IO.Compression.FileSystem) - Base Class Library - David Anderson