Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - Using System.IO.Packaging to generate a ZIP file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:WindowsNotepad.exe");
            AddFileToZip("Output.zip", @"C:WindowsSystem32Calc.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);
                    }
                }
            }
        }              
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...