ZipArchive 类

定义

表示 Zip 存档格式中的一个压缩文件包。Represents a package of compressed files in the zip archive format.

public ref class ZipArchive : IDisposable
public class ZipArchive : IDisposable
type ZipArchive = class
    interface IDisposable
Public Class ZipArchive
Implements IDisposable
继承
ZipArchive
实现

示例

第一个示例演示如何使用流创建新条目并写入该条目。The first example shows how to create a new entry and write to it by using a stream.

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Module Module1

    Sub Main()
        Using zipToOpen As FileStream = New FileStream("c:\users\exampleuser\release.zip", FileMode.Open)
            Using archive As ZipArchive = New ZipArchive(zipToOpen, ZipArchiveMode.Update)
                Dim readmeEntry As ZipArchiveEntry = archive.CreateEntry("Readme.txt")
                Using writer As StreamWriter = New StreamWriter(readmeEntry.Open())
                    writer.WriteLine("Information about this package.")
                    writer.WriteLine("========================")
                End Using
            End Using
        End Using
    End Sub

End Module

下面的示例演示如何打开 zip 存档并循环访问项的集合。The following example shows how to open a zip archive and iterate through the collection of entries.

using System;
using System.IO;
using System.IO.Compression;

class Program
{
    static void Main(string[] args)
    {
        string zipPath = @".\result.zip";

        Console.WriteLine("Provide path where to extract the zip file:");
        string extractPath = Console.ReadLine();

        // Normalizes the path.
        extractPath = Path.GetFullPath(extractPath);

        // Ensures that the last character on the extraction path
        // is the directory separator char. 
        // Without this, a malicious zip file could try to traverse outside of the expected
        // extraction path.
        if (!extractPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            extractPath += Path.DirectorySeparatorChar;

        using (ZipArchive archive = ZipFile.OpenRead(zipPath))
        {
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                {
                    // Gets the full path to ensure that relative segments are removed.
                    string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));

                    // Ordinal match is safest, case-sensitive volumes can be mounted within volumes that
                    // are case-insensitive.
                    if (destinationPath.StartsWith(extractPath, StringComparison.Ordinal))
                        entry.ExtractToFile(destinationPath);
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Module Module1

    Sub Main()
        Dim zipPath As String = ".\result.zip"

        Console.WriteLine("Provide path where to extract the zip file:")
        Dim extractPath As String = Console.ReadLine()

        ' Normalizes the path.
        extractPath = Path.GetFullPath(extractPath)

        ' Ensures that the last character on the extraction path
        ' is the directory separator char. 
        ' Without this, a malicious zip file could try to traverse outside of the expected
        ' extraction path.
        If Not extractPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) Then
            extractPath += Path.DirectorySeparatorChar
        End If

        Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
            For Each entry As ZipArchiveEntry In archive.Entries
                If entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then

                    ' Gets the full path to ensure that relative segments are removed.
                    Dim destinationPath As String = Path.GetFullPath(Path.Combine(extractPath, entry.FullName))
                    
                    ' Ordinal match is safest, case-sensitive volumes can be mounted within volumes that
                    ' are case-insensitive.
                    If destinationPath.StartsWith(extractPath, StringComparison.Ordinal) Then 
                        entry.ExtractToFile(destinationPath)
                    End If

                End If
            Next
        End Using
    End Sub

End Module

第三个示例演示如何使用扩展方法从现有文件在 zip 存档中创建新条目,并提取存档内容。The third example shows how to use extension methods to create a new entry in a zip archive from an existing file and extract the archive contents. 若要执行代码,必须引用 System.IO.Compression.FileSystem 程序集。You must reference the System.IO.Compression.FileSystem assembly to execute the code.

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string zipPath = @"c:\users\exampleuser\start.zip";
            string extractPath = @"c:\users\exampleuser\extract";
            string newFile = @"c:\users\exampleuser\NewFile.txt";
            
            using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
            {
                archive.CreateEntryFromFile(newFile, "NewEntry.txt");
                archive.ExtractToDirectory(extractPath);
            } 
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Module Module1

    Sub Main()
        Dim zipPath As String = "c:\users\exampleuser\end.zip"
        Dim extractPath As String = "c:\users\exampleuser\extract"
        Dim newFile As String = "c:\users\exampleuser\NewFile.txt"

        Using archive As ZipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update)
            archive.CreateEntryFromFile(newFile, "NewEntry.txt", CompressionLevel.Fastest)
            archive.ExtractToDirectory(extractPath)
        End Using
    End Sub

End Module

注解

用于处理 zip 存档及其文件项的方法分布在三个类中: ZipFileZipArchiveZipArchiveEntryThe methods for manipulating zip archives and their file entries are spread across three classes: ZipFile, ZipArchive, and ZipArchiveEntry.

To 使用Use
从目录创建 zip 存档Create a zip archive from a directory ZipFile.CreateFromDirectory
将 zip 存档的内容提取到目录Extract the contents of a zip archive to a directory ZipFile.ExtractToDirectory
将新文件添加到现有 zip 存档Add new files to an existing zip archive ZipArchive.CreateEntry
从 zip 存档中检索文件Retrieve a file from a zip archive ZipArchive.GetEntry
检索 zip 存档中的所有文件Retrieve all the files from a zip archive ZipArchive.Entries
打开 zip 存档中包含的单个文件的流Open a stream to a single file contained in a zip archive ZipArchiveEntry.Open
删除 zip 存档中的文件Delete a file from a zip archive ZipArchiveEntry.Delete

当你创建新项时,该文件将被压缩并添加到 zip 包。When you create a new entry, the file is compressed and added to the zip package. 使用 CreateEntry 方法,您可以在添加项时指定目录层次结构。The CreateEntry method enables you to specify a directory hierarchy when adding the entry. 在 zip 包中包含新项的相对路径。You include the relative path of the new entry within the zip package. 例如,使用 AddedFolder\NewFile.txt 的相对路径创建新条目将在名为 AddedFolder 的目录中创建一个压缩的文本文件。For example, creating a new entry with a relative path of AddedFolder\NewFile.txt creates a compressed text file in a directory named AddedFolder.

如果在项目中引用 System.IO.Compression.FileSystem 程序集,则可以访问 ZipArchive 类的四个扩展方法(来自 ZipFileExtensions 类): CreateEntryFromFile(ZipArchive, String, String)CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)ExtractToDirectory(ZipArchive, String)ExtractToDirectory(ZipArchive, String, Boolean) (可在 .NET Core 2.0 及更高版本中使用)。If you reference the System.IO.Compression.FileSystem assembly in your project, you can access four extension methods (from the ZipFileExtensions class) for the ZipArchive class: CreateEntryFromFile(ZipArchive, String, String), CreateEntryFromFile(ZipArchive, String, String, CompressionLevel), ExtractToDirectory(ZipArchive, String), and ExtractToDirectory(ZipArchive, String, Boolean) (available in .NET Core 2.0 and later versions). 使用这些扩展方法可以将项的内容压缩和解压缩到文件中。These extension methods enable you to compress and decompress the contents of the entry to a file. System.IO.Compression.FileSystem 程序集不适用于 Windows 8.x 应用商店Windows 8.x Store 应用。The System.IO.Compression.FileSystem assembly is not available for Windows 8.x 应用商店Windows 8.x Store apps. Windows 8.x 应用商店Windows 8.x Store 应用中,可以通过使用 DeflateStreamGZipStream 类来压缩和解压缩文件,也可以使用 Windows 运行时Windows Runtime 类型压缩机解压缩程序。In Windows 8.x 应用商店Windows 8.x Store apps, you can compress and decompress files by using the DeflateStream or GZipStream class, or you can use the Windows 运行时Windows Runtime types Compressor and Decompressor.

构造函数

ZipArchive(Stream)

从指定的流初始化 ZipArchive 类的新实例。Initializes a new instance of the ZipArchive class from the specified stream.

ZipArchive(Stream, ZipArchiveMode)

从指定的流并使用指定的模式初始化 ZipArchive 类的新实例。Initializes a new instance of the ZipArchive class from the specified stream and with the specified mode.

ZipArchive(Stream, ZipArchiveMode, Boolean)

对于指定的模式,初始化指定流上的 ZipArchive 类的新实例,并选择性地使流保持打开状态。Initializes a new instance of the ZipArchive class on the specified stream for the specified mode, and optionally leaves the stream open.

ZipArchive(Stream, ZipArchiveMode, Boolean, Encoding)

对于指定的模式,初始化指定流上的 ZipArchive 类的新实例,使用项名的指定编码,并选择性地使流保持打开状态。Initializes a new instance of the ZipArchive class on the specified stream for the specified mode, uses the specified encoding for entry names, and optionally leaves the stream open.

属性

Entries

获取 zip 存档中当前存在的项的集合。Gets the collection of entries that are currently in the zip archive.

Mode

获取描述 zip 存档可在项上执行的操作类型的一个值。Gets a value that describes the type of action the zip archive can perform on entries.

方法

CreateEntry(String)

创建在 zip 存档中有指定路径和项名的空项。Creates an empty entry that has the specified path and entry name in the zip archive.

CreateEntry(String, CompressionLevel)

创建在 zip 存档中有指定项名和压缩级别的空项。Creates an empty entry that has the specified entry name and compression level in the zip archive.

Dispose()

释放 ZipArchive 类的当前实例使用的资源。Releases the resources used by the current instance of the ZipArchive class.

Dispose(Boolean)

Dispose()Finalize() 方法调用,以释放 ZipArchive 类的当前实例使用的未托管资源,并选择性地完成存档的写入和释放托管资源。Called by the Dispose() and Finalize() methods to release the unmanaged resources used by the current instance of the ZipArchive class, and optionally finishes writing the archive and releases the managed resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEntry(String)

在 zip 存档中检索指定项的包装。Retrieves a wrapper for the specified entry in the zip archive.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

扩展方法

CreateEntryFromFile(ZipArchive, String, String)

通过压缩并将其添加到邮编存档的存档文件。Archives a file by compressing it and adding it to the zip archive.

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

通过使用指定压缩级别压缩并将其添加到邮编存档的存档文件。Archives a file by compressing it using the specified compression level and adding it to the zip archive.

ExtractToDirectory(ZipArchive, String)

将 zip 存档中的所有文件都解压缩到文件系统的一个目录下。Extracts all the files in the zip archive to a directory on the file system.

ExtractToDirectory(ZipArchive, String, Boolean)

将存档中的所有文件都解压缩到文件系统的一个目录下。Extracts all of the files in the archive to a directory on the file system.

适用于

另请参阅