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 封存和其檔案專案的方法會散佈到三個ZipFile類別ZipArchive:、 ZipArchiveEntry和。The 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中的元件, 您可以ZipFileExtensionsZipArchive類別存取四個擴充方法 (來自類別): CreateEntryFromFile(ZipArchive, String, String)CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)ExtractToDirectory(ZipArchive, String)ExtractToDirectory(ZipArchive, String, Boolean) (適用于 .net核心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. Windows 8.x 市集Windows 8.x Store應用System.IO.Compression.FileSystem程式無法使用此元件。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 [應用程式] 中, 您可以DeflateStream使用或GZipStream類別來壓縮和解壓縮檔案, 或者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 類別之目前執行個體所使用的 Unmanaged 資源,並選擇性完成封存的寫入以及釋放 Managed 資源。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 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

擴充方法

CreateEntryFromFile(ZipArchive, String, String)

透過將檔案壓縮並加入至 zip 封存的方式進行封存。Archives a file by compressing it and adding it to the zip archive.

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

透過將檔案以指定之壓縮等級壓縮並加入至 zip 封存的方式進行封存。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.

適用於

另請參閱