Creating a folder inside the ZIP file with System.IO.Packaging

Jon Galloway posted a great article how to zip files using .NET without any external library, after that many people were asking how to create a directory inside that zip file to organized the ZIP

http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx?CommentPosted=true#commentmessage

I added the code into the comments yet for easy copy and paste, please find the code below, now is a parameter for the method.

 

private static void AddFileToZip(string zipFilename, string fileToAdd, string sDirectory)
        {
            using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
            {
                string destFilename = ".\\" + sDirectory + "\\" + Path.GetFileName(fileToAdd);
                Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
                if (zip.PartExists(uri))
                {
                    zip.DeletePart(uri);
                }
                PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);

                using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                {
                    using (Stream dest = part.GetStream())
                    {
                        CopyStream(fileStream, dest);
                    }
                }
            }
        }

 

Cheers

Al

Follow me in twitter | bookmark me | Subscribe to my feed | Add stats to your blog

Published Monday, May 18, 2009 9:29 PM by albertpascual
Filed under: , , , ,

Comments

# Creating a folder inside the ZIP file with System.IO.Packaging - Al Pascual

Tuesday, May 19, 2009 11:03 AM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# Links 2009-06-13

Friday, June 12, 2009 8:11 PM by Community Blogs

SharePoint Uploading Files to SharePoint Server 2007 from ASP.NET Web Applications by Using the HTTP

Leave a Comment

(required) 
(required) 
(optional)
(required)