Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using System.IO.Packaging to generate a ZIP file

Tags:

c#

.net

zip

I know that the likes of the DotNetZip or SharpZipLib libraries are usually recommended for creating ZIP files in a .net language (C# in my case), but it's not impossible to use System.IO.Packaging to generate a ZIP file. I thought it might be nice to try and develop a routine in C# which could do it, without the need to download any external libraries. Does anyone have a good example of a method or methods that will use System.IO.Packaging to generate a ZIP file?

like image 451
Jez Avatar asked Jun 17 '11 13:06

Jez


1 Answers

let me google this for you -> system.io.packaging+generate+zip

first link http://weblogs.asp.net/jongalloway//creating-zip-archives-in-net-without-an-external-library-like-sharpziplib

using System;
using System.IO;
using System.IO.Packaging;

namespace ZipSample
{
    class Program
    {
        static void Main(string[] args)
        {
            AddFileToZip("Output.zip", @"C:\Windows\Notepad.exe");
            AddFileToZip("Output.zip", @"C:\Windows\System32\Calc.exe");
        }

        private static void AddFileToZip(string zipFilename, string fileToAdd, CompressionOption compression = CompressionOption.Normal)
        {
            using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
            {
                string destFilename = ".\\" + Path.GetFileName(fileToAdd);
                Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
                if (zip.PartExists(uri))
                {
                    zip.DeletePart(uri);
                }
                PackagePart part = zip.CreatePart(uri, "", compression);
                using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                {
                    using (Stream dest = part.GetStream())
                    {
                        fileStream.CopyTo(dest);
                    }
                }
            }
        }              
    }
}
like image 70
RamonBoza Avatar answered Sep 20 '22 10:09

RamonBoza