Creating a Zip File in C#

2/27/2011

I recently ran into a request in a project where I needed to zip up a number of files on the fly and email them to a specific individual. The email part was easy but I thought that the zip file part of the request would be a bit more difficult. I mean there is SharpZipLib, but that uses the GPL and that instantly killed that as an option for this product (I didn't make that requirement, it was forced upon me). At that point I thought that I was rather screwed until I found out that .Net has the ability to create zip files built into the system. Specifically if you look at the System.IO.Packaging portion of .Net (which is in the winbase DLL), you will find the ZipPackage class. This class, plus a couple others, allows you to package files together (by default into a zip file). So I spent about an hour and created a basic class to accomplish what I needed:

   1: /*
   2: Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>
   3: 
   4: Permission is hereby granted, free of charge, to any person obtaining a copy
   5: of this software and associated documentation files (the "Software"), to deal
   6: in the Software without restriction, including without limitation the rights
   7: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   8: copies of the Software, and to permit persons to whom the Software is
   9: furnished to do so, subject to the following conditions:
  10: 
  11: The above copyright notice and this permission notice shall be included in
  12: all copies or substantial portions of the Software.
  13: 
  14: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20: THE SOFTWARE.*/
  21:  
  22: #region Usings
  23: using System;
  24: using System.Collections.Generic;
  25: using System.Linq;
  26: using System.Text;
  27: using System.IO.Packaging;
  28: using System.IO;
  29: #endregion
  30:  
  31: namespace Utilities.FileFormats.Zip
  32: {
  33:     /// <summary>
  34:     /// Helper class for dealing with zip files
  35:     /// </summary>
  36:     public class ZipFile : IDisposable
  37:     {
  38:         #region Constructor
  39:  
  40:         /// <summary>
  41:         /// Constructor
  42:         /// </summary>
  43:         /// <param name="FilePath">Path to the zip file</param>
  44:         /// <param name="Overwrite">Should the zip file be overwritten?</param>
  45:         public ZipFile(string FilePath, bool Overwrite)
  46:         {
  47:             if (string.IsNullOrEmpty(FilePath))
  48:                 throw new ArgumentNullException("FilePath");
  49:             ZipFileStream = new FileStream(FilePath, Overwrite ? FileMode.Create : FileMode.OpenOrCreate);
  50:         }
  51:  
  52:         #endregion
  53:  
  54:         #region Properties
  55:  
  56:         /// <summary>
  57:         /// Zip file's FileStream
  58:         /// </summary>
  59:         protected virtual FileStream ZipFileStream { get; set; }
  60:  
  61:         #endregion
  62:  
  63:         #region Functions
  64:  
  65:         /// <summary>
  66:         /// Adds a folder to the zip file
  67:         /// </summary>
  68:         /// <param name="Folder">Folder to add</param>
  69:         public virtual void AddFolder(string Folder)
  70:         {
  71:             if (string.IsNullOrEmpty(Folder))
  72:                 throw new ArgumentNullException("Folder");
  73:             if (Folder.EndsWith(@"\"))
  74:                 Folder = Folder.Remove(Folder.Length - 1);
  75:             using (Package Package = ZipPackage.Open(ZipFileStream, FileMode.OpenOrCreate))
  76:             {
  77:                 List<FileInfo> Files = Utilities.IO.FileManager.FileList(Folder, true);
  78:                 foreach (FileInfo File in Files)
  79:                 {
  80:                     string FilePath = File.FullName.Replace(Folder, "");
  81:                     AddFile(FilePath, File, Package);
  82:                 }
  83:             }
  84:         }
  85:  
  86:         /// <summary>
  87:         /// Adds a file to the zip file
  88:         /// </summary>
  89:         /// <param name="File">File to add</param>
  90:         public virtual void AddFile(string File)
  91:         {
  92:             if (string.IsNullOrEmpty(File))
  93:                 throw new ArgumentNullException("File");
  94:             if (!Utilities.IO.FileManager.FileExists(File))
  95:                 throw new ArgumentException("File");
  96:             using (Package Package = ZipPackage.Open(ZipFileStream))
  97:             {
  98:                 AddFile(File, new FileInfo(File), Package);
  99:             }
 100:         }
 101:  
 102:         /// <summary>
 103:         /// Uncompresses the zip file to the specified folder
 104:         /// </summary>
 105:         /// <param name="Folder">Folder to uncompress the file in</param>
 106:         public virtual void UncompressFile(string Folder)
 107:         {
 108:             if (string.IsNullOrEmpty(Folder))
 109:                 throw new ArgumentNullException(Folder);
 110:             Utilities.IO.FileManager.CreateDirectory(Folder);
 111:             using (Package Package = ZipPackage.Open(ZipFileStream, FileMode.Open, FileAccess.Read))
 112:             {
 113:                 foreach (PackageRelationship Relationship in Package.GetRelationshipsByType("http://schemas.microsoft.com/opc/2006/sample/document"))
 114:                 {
 115:                     Uri UriTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), Relationship.TargetUri);
 116:                     PackagePart Document = Package.GetPart(UriTarget);
 117:                     Extract(Document, Folder);
 118:                 }
 119:                 if (File.Exists(Folder + @"\[Content_Types].xml"))
 120:                     File.Delete(Folder + @"\[Content_Types].xml");
 121:             }
 122:         }
 123:  
 124:         /// <summary>
 125:         /// Extracts an individual file
 126:         /// </summary>
 127:         /// <param name="Document">Document to extract</param>
 128:         /// <param name="Folder">Folder to extract it into</param>
 129:         protected virtual void Extract(PackagePart Document, string Folder)
 130:         {
 131:             if (string.IsNullOrEmpty(Folder))
 132:                 throw new ArgumentNullException(Folder);
 133:             string Location = Folder + System.Web.HttpUtility.UrlDecode(Document.Uri.ToString()).Replace('\\', '/');
 134:             Utilities.IO.FileManager.CreateDirectory(Path.GetDirectoryName(Location));
 135:             byte[] Data = new byte[1024];
 136:             using (FileStream FileStream = new FileStream(Location, FileMode.Create))
 137:             {
 138:                 Stream DocumentStream = Document.GetStream();
 139:                 while (true)
 140:                 {
 141:                     int Size = DocumentStream.Read(Data, 0, 1024);
 142:                     FileStream.Write(Data, 0, Size);
 143:                     if (Size != 1024)
 144:                         break;
 145:                 }
 146:                 FileStream.Close();
 147:             }
 148:         }
 149:  
 150:         /// <summary>
 151:         /// Adds a file to the zip file
 152:         /// </summary>
 153:         /// <param name="File">File to add</param>
 154:         /// <param name="FileInfo">File information</param>
 155:         /// <param name="Package">Package to add the file to</param>
 156:         protected virtual void AddFile(string File, FileInfo FileInfo, Package Package)
 157:         {
 158:             if (string.IsNullOrEmpty(File))
 159:                 throw new ArgumentNullException("File");
 160:             if (!Utilities.IO.FileManager.FileExists(FileInfo.FullName))
 161:                 throw new ArgumentException("File");
 162:             Uri UriPath = PackUriHelper.CreatePartUri(new Uri(File, UriKind.Relative));
 163:             PackagePart PackagePart = Package.CreatePart(UriPath, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum);
 164:             byte[] Data = null;
 165:             Utilities.IO.FileManager.GetFileContents(FileInfo.FullName, out Data);
 166:             PackagePart.GetStream().Write(Data, 0, Data.Count());
 167:             Package.CreateRelationship(PackagePart.Uri, TargetMode.Internal, "http://schemas.microsoft.com/opc/2006/sample/document");
 168:         }
 169:  
 170:         #endregion
 171:  
 172:         #region IDisposable Members
 173:  
 174:         public void Dispose()
 175:         {
 176:             if (ZipFileStream != null)
 177:             {
 178:                 ZipFileStream.Close();
 179:                 ZipFileStream.Dispose();
 180:                 ZipFileStream = null;
 181:             }
 182:         }
 183:  
 184:         #endregion
 185:     }
 186: }

If you'll notice there isn't much actual code there. Just an AddFolder function, AddFile, and Uncompress (plus two protected functions that they use). In order to use it you just create the object like this:

   1: using (Utilities.FileFormats.Zip.ZipFile File = new Utilities.FileFormats.Zip.ZipFile("ZIPFILENAME.zip", true))
   2: {
   3:     File.AddFolder("FOLDERTOADD");
   4: }

And that's it, you add the files/folders that you want to the zip file and you're done (the ZipFile class actually handles outputting everything to a file). And we can unzip the file with the following code:

   1: using (Utilities.FileFormats.Zip.ZipFile File = new Utilities.FileFormats.Zip.ZipFile("ZIPFILENAME.zip", false))
   2: {
   3:     File.UncompressFile("FOLDERTOUNCOMPRESSWITHIN");
   4: }
And that's it. It accomplished what I needed and was extremely simple. Note that the code above doesn't work on all zip files but the zip files that you create can be opened with other apps. Anyway, try out the code (you may want to go to my utility library's site and check for updates as I've added the code there), leave feedback, and happy coding.


Comments

Nicholas Carey
December 29, 2011 1:41 PM
Why not use DotNetZip from http://dotnetzip.codeplex.com/It's not GPL'd, but it is under the "Microsoft Public License". Far easier than trying to stumble through the mess that is System.IO.Packaging. All done in C#. Speeds comparable to Info-Zip's Zip/Unzip -- http://www.info-zip.org/ -- compression ratios ditto.Much more flexible and cleaner interface IMHO.