ZipArchive 类

定义

表示 Zip 存档格式中的一个压缩文件包。

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

注解

用于操作 zip 存档及其文件条目的方法分布在三个类中:ZipFileZipArchiveZipArchiveEntry

功能 使用
从目录创建 zip 存档 ZipFile.CreateFromDirectory
将 zip 存档的内容提取到目录 ZipFile.ExtractToDirectory
将新文件添加到现有 zip 存档 ZipArchive.CreateEntry
从 zip 存档检索文件 ZipArchive.GetEntry
从 zip 存档检索所有文件 ZipArchive.Entries
打开流到 zip 存档中包含的单个文件 ZipArchiveEntry.Open
从 zip 存档中删除文件 ZipArchiveEntry.Delete

创建新条目时,文件将被压缩并添加到 zip 包。 使用此方法 CreateEntry 可以在添加条目时指定目录层次结构。 在 zip 包中包含新条目的相对路径。 例如,使用相对路径创建新条目,以便在 AddedFolder\NewFile.txt 名为 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 及更高版本中提供的 () 。 借助这些扩展方法,可以压缩和解压缩文件条目的内容。 程序集System.IO.Compression.FileSystem不适用于 Windows 8.x 应用商店应用。 在 Windows 8.x 应用商店应用中,可以使用或类压缩和解压缩文件DeflateStream,也可以使用Windows 运行时类型和CompressorDecompressorGZipStream

示例

第一个示例演示如何使用流创建新条目并写入该条目。

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 存档并循环访问条目集合。

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 存档中创建一个新条目,并提取存档内容。 必须引用 System.IO.Compression.FileSystem 程序集才能执行代码。

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

构造函数

ZipArchive(Stream)

从指定的流初始化 ZipArchive 类的新实例。

ZipArchive(Stream, ZipArchiveMode)

从指定的流并使用指定的模式初始化 ZipArchive 类的新实例。

ZipArchive(Stream, ZipArchiveMode, Boolean)

对于指定的模式,初始化指定流上的 ZipArchive 类的新实例,并选择性地使流保持打开状态。

ZipArchive(Stream, ZipArchiveMode, Boolean, Encoding)

对于指定的模式,初始化指定流上的 ZipArchive 类的新实例,使用项名的指定编码,并选择性地使流保持打开状态。

属性

Comment

获取或设置可选的存档注释。

Entries

获取 zip 存档中当前存在的项的集合。

Mode

获取描述 Zip 存档操作类型在实体上执行的值。

方法

CreateEntry(String)

创建在 zip 存档中有指定路径和项名的空项。

CreateEntry(String, CompressionLevel)

创建在 zip 存档中有指定项名和压缩级别的空项。

Dispose()

释放 ZipArchive 类的当前实例使用的资源。

Dispose(Boolean)

Dispose()Finalize() 方法调用,以释放 ZipArchive 类的当前实例使用的未托管资源,并选择性地完成存档的写入和释放托管资源。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetEntry(String)

在 zip 存档中检索指定项的包装。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

扩展方法

CreateEntryFromFile(ZipArchive, String, String)

通过压缩并将其添加到邮编存档的存档文件。

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

通过使用指定压缩级别压缩并将其添加到邮编存档的存档文件。

ExtractToDirectory(ZipArchive, String)

将 zip 存档中的所有文件都解压缩到文件系统的一个目录下。

ExtractToDirectory(ZipArchive, String, Boolean)

将存档中的所有文件都解压缩到文件系统的一个目录下。

适用于

另请参阅