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 Store 應用程式。 在 Windows 8.x Store 應用程式中,您可以使用 或 類別壓縮和解壓縮檔案 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 類別之目前執行個體所使用的 Unmanaged 資源,並選擇性完成封存的寫入以及釋放 Managed 資源。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetEntry(String)

在 zip 封存中擷取指定項目的包裝函式。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

擴充方法

CreateEntryFromFile(ZipArchive, String, String)

透過將檔案壓縮並加入至 zip 封存的方式進行封存。

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

透過將檔案以指定之壓縮等級壓縮並加入至 zip 封存的方式進行封存。

ExtractToDirectory(ZipArchive, String)

將 zip 封存中的所有檔案都解壓縮到檔案系統上的目錄。

ExtractToDirectory(ZipArchive, String, Boolean)

將封存中的所有檔案解壓縮到檔案系統上目錄。

適用於

另請參閱