使用System.IO.Packaging程序生成的ZIP文件文件、程序、IO、System

由网友(无心√)分享简介:我知道DotNetZip或SharpZipLib库的喜欢,通常建议在.NET语言创建ZIP文件(C#在我的情况),但它不是的不可能的使用 System.IO.Packaging程序来生成一个ZIP文件。我想这可能是不错的尝试,并制定了常规的C#这能做到这一点,而无需下载任何外部库。有没有人有一种方法或方法将使用一个很好...

我知道DotNetZip或SharpZipLib库的喜欢,通常建议在.NET语言创建ZIP文件(C#在我的情况),但它不是的不可能的使用 System.IO.Packaging程序来生成一个ZIP文件。我想这可能是不错的尝试,并制定了常规的C#这能做到这一点,而无需下载任何外部库。有没有人有一种方法或方法将使用一个很好的例子 System.IO.Packaging程序来生成一个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?

推荐答案

让我谷歌为你 - > System.IO.Packaging程序+生成+拉链

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

第一个链接 http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx

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 const long BUFFER_SIZE = 4096;

        private static void AddFileToZip(string zipFilename, string fileToAdd)
        {
            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, "",CompressionOption.Normal);
                using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                {
                    using (Stream dest = part.GetStream())
                    {
                        CopyStream(fileStream, dest);
                    }
                }
            }
        }

        private static void CopyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
        {
            long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
            byte[] buffer = new byte[bufferSize];
            int bytesRead = 0;
            long bytesWritten = 0;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
                bytesWritten += bytesRead;
            }
        }
    }
}
阅读全文

相关推荐

最新文章