.net 如何使用 System.IO.Compression 读/写 ZIP 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/184309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:16:27  来源:igfitidea点击:

How to use System.IO.Compression to read/write ZIP files?

.netcompressionzip

提问by Chris Pietschmann

I know there are libraries out there for working with ZIP files. And, you can alternatively use the functionality built into Windows for working ZIP files.

我知道有一些库可以处理 ZIP 文件。而且,您也可以使用 Windows 内置的功能来处理 ZIP 文件

But, I'm wondering if anyone has worked out how to use the tools built into the System.IO.Compression namespace within .NET for reading/writing ZIP files? Or, is it not possible using only this namespace?

但是,我想知道是否有人已经研究出如何使用 .NET 中 System.IO.Compression 命名空间中内置的工具来读取/写入 ZIP 文件?或者,仅使用这个命名空间是不可能的?

UPDATED: I've seem someone comment that the System.IO.Packaging namespace might be usefull with this also. Does anyone know exactly how to do it?

更新:我似乎有人评论说 System.IO.Packaging 命名空间也可能对此有用。有谁知道具体怎么做?

采纳答案by Dave Moore

MSDN has a complete examplehttp://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspxusing the ZipPackage class. Requires .NET 3.5.

MSDN 有一个使用 ZipPackage 类的完整示例http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx。需要 .NET 3.5。

回答by Chris Pietschmann

Dave, very nice!! I didn't know that was in there.

戴夫,非常好!!我不知道那在那里。

Now that I know what to look for, I was able to find an article with a small code sample on how to use it: http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx

现在我知道要查找什么了,我找到了一篇关于如何使用它的小代码示例的文章:http: //weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip -archives-in-net-without-an-external-library-like-sharpziplib.aspx

On a related note, I also found the DotNetZip projectthat looks extremely easy to use.

在相关说明中,我还发现DotNetZip 项目看起来非常易于使用。

回答by Cheeso

You will want to use a third-party library, like http://www.codeplex.com/DotNetZip, rather than trying to use GZipStream or DeflateStream to read a zip file.

您将需要使用第三方库,例如http://www.codeplex.com/DotNetZip,而不是尝试使用 GZipStream 或 DeflateStream 来读取 zip 文件。

The ***Stream classes in .NET can let you read or write compressed streams of bytes. These classes DO NOT read or write zip files. The zip file is compressed data surrounded by "an envelope" or a header. Think of it as metadata - it includes the name of the file, timestamp, CRC, and a bunch of other stuff. The **Stream classes produce only the stream of compressed data, and do not know how to produce or consume the metadata, which is described in the PKZip format specification maintained by PKWare.

.NET 中的 ***Stream 类可以让您读取或写入压缩的字节流。这些类不读取或写入 zip 文件。zip 文件是由“信封”或标题包围的压缩数据。将其视为元数据 - 它包括文件名、时间戳、CRC 和一堆其他内容。**Stream 类只生成压缩数据流,不知道如何生成或消费元数据,这在 PKWare 维护的 PKZip 格式规范中进行了描述。

Third party libraries like DotNetZip handle the metadata in a ZIP archive. They may or may not use the System.IO.Compression.DeflateStream() class to produced the compressed stream of bytes. In previous releases, for example, DotNetZip used the built-in DeflateStream. As of v1.7, DotNetZip includes its own DeflateStream which is more efficient than the one shipped in the .NET Framework. As an added benefit, the embedded DeflateStream in DotNetZip allows DotNetZip to be used on the .NET Compact Framework 2.0, which lacks a System.IO.Compression.DeflateStream. (it was added in Compact Framework 3.5)

DotNetZip 等第三方库处理 ZIP 存档中的元数据。他们可能会也可能不会使用 System.IO.Compression.DeflateStream() 类来生成压缩的字节流。例如,在以前的版本中,DotNetZip 使用了内置的 DeflateStream。从 v1.7 开始,DotNetZip 包含自己的 DeflateStream,它比 .NET Framework 中提供的更高效。作为一个额外的好处,DotNetZip 中嵌入的 DeflateStream 允许 DotNetZip 用于缺少 System.IO.Compression.DeflateStream 的 .NET Compact Framework 2.0。(它是在 Compact Framework 3.5 中添加的)

There's a good forum on the DotNetZip site if you have more questions. Example C# code:

如果您有更多问题,DotNetZip 站点上有一个很好的论坛。示例 C# 代码:

    try
    {
        using (ZipFile zip = new ZipFile())
        {
            zip.AddDirectory(DirectoryToZip); // recurses subdirs
            zip.Save(Filename);
        }
    }
    catch (System.Exception ex1)
    {
        System.Console.Error.WriteLine("exception: " + ex1);
    }

回答by Christopher Currens

Since .NET 4.5, Microsoft has offered the ZipArchiveclass to the System.IO.Compressionnamespace. Unlike other classes in that namespace, though, like GZipStreamand Deflatestream, the ZipArchiverequires a reference to the System.IO.Compression.dllassembly.

从 .NET 4.5 开始,Microsoft为命名空间提供了ZipArchiveSystem.IO.Compression。但是,与该命名空间中的其他类不同,像GZipStreamDeflate流一样,它ZipArchive需要对 System.IO.Compression.dll程序集的引用

It's fairly simple to use, and the link above to MSDN provides some good examples.

它使用起来相当简单,上面的 MSDN 链接提供了一些很好的例子。

Additionally, Microsoft has created the Microsoft Compression NuGet package, which adds support for ZipArchiveand related classes to Windows Phone 8 and other Portable Class Libraries

此外,Microsoft 还创建了Microsoft Compression NuGet 包,它增加了ZipArchive对 Windows Phone 8 和其他可移植类库的支持和相关类

回答by Christopher Piper

An older thread, I know, but I'd like to point out that .NET 4.5 added extensive improvements to system.io.compression. It can now manipulate .zip files quite well, even down to exposing individual files within the zip as streams capable or read and write without the step of extracting and compressing the files.

我知道一个较旧的线程,但我想指出 .NET 4.5 对 system.io.compression 进行了大量改进。它现在可以很好地处理 .zip 文件,甚至可以将 zip 中的单个文件公开为能够读取和写入的流,而无需提取和压缩文件的步骤。

回答by Sean Hanley

Yes, I've used it in the past. I sub-classed DataSetonce to support persisting itself out to a file (via the ReadXML/WriteXMLmethod). As an added bonus, I decided to allow it to be, optionally, compressed if desired (this, as you all should already know, is extremely effective with textual data like XML).

是的,我过去用过它。我曾经对DataSet进行子类以支持将其自身持久化到文件中(通过ReadXML/ WriteXML方法)。作为一个额外的好处,我决定允许它在需要时进行可选的压缩(你们都应该已经知道,这对于像 XML 这样的文本数据非常有效)。

I used the GZipStreamclass (it was my understanding at the time that the related DeflateStreamwas merely GZip without header information, or some such — I'm sure someone could correct me on this). It works quite simply by piggy-backing on top of another stream and thus you then use the GZipStream in its place. In my case, it was piggy-backing on a FileStream.

我使用了GZipStream类(当时我的理解是,相关的DeflateStream只是没有标头信息的 GZip,或者类似的东西——我相信有人可以纠正我)。它的工作原理非常简单,通过搭载在另一个流的顶部,因此您可以在它的位置使用 GZipStream。就我而言,它捎带在 FileStream 上。

Given a MemoryStreamto be filled with the output of myDataSet.WriteXML(), I did something like the following:

给定一个要用 的输出填充的MemoryStreammyDataSet.WriteXML(),我做了如下的事情:

if (CompressData)
{
    // Write to memory
    mStream = new MemoryStream();
    Save(mStream);
    mStream.Seek(0, SeekOrigin.Begin);

    // Filter that through a GZipStream and then to file
    fStream = new FileStream(Path.Combine(CacheFilePath, FileName + ".gz"),
                             FileMode.OpenOrCreate);
    zipStream = new GZipStream(fStream, CompressionMode.Compress, true);

    Pump(mStream, zipStream);
}
else
{
    // Write straight to file
    fStream = new FileStream(Path.Combine(CacheFilePath, FileName),
                             FileMode.OpenOrCreate);
    Save(fStream);
}

Where Save()and Pump()are simple methods like the following:

WhereSave()Pump()are 简单的方法如下:

private void Pump(Stream input, Stream output)
{
    int n;
    byte[] bytes = new byte[4096]; // 4KiB at a time

    while ((n = input.Read(bytes, 0, bytes.Length)) != 0)
    {
        output.Write(bytes, 0, n);
    }
}

public void Save(Stream stream)
{
    AcceptChanges();

    WriteXml(stream, XmlWriteMode.WriteSchema);
}

回答by muhammedkasva

    public static void zIpDatabseFile(string srcPath, string destPath)
    {//This is for  Zip a File
        using (var source = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (var dest = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write))
        using (var zip = new GZipStream(dest, CompressionMode.Compress))
        {
            source.CopyTo(zip);
        }
    }
    public static void uNzIpDatabaseFile(string SrcPath, string DestPath)
    {// This is for unzip a files.
        using (var source = new FileStream(SrcPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (var dest = new FileStream(DestPath, FileMode.OpenOrCreate, FileAccess.Write))
        using (var zip = new GZipStream(source, CompressionMode.Decompress))
        {
            zip.CopyTo(dest);
        }
    }