ZipArchive Třída

Definice

Představuje balíček komprimovaných souborů ve formátu zip archivu.

public ref class ZipArchive : IDisposable
public class ZipArchive : IDisposable
type ZipArchive = class
    interface IDisposable
Public Class ZipArchive
Implements IDisposable
Dědičnost
ZipArchive
Implementuje

Poznámky

Metody pro manipulaci s archivy ZIP a jejich položkami souborů jsou rozloženy do tří tříd: ZipFile, ZipArchivea ZipArchiveEntry.

Záměr Použití
Create archivu zip z adresáře ZipFile.CreateFromDirectory
Extrahování obsahu archivu zip do adresáře ZipFile.ExtractToDirectory
Přidání nových souborů do existujícího archivu zip ZipArchive.CreateEntry
Načtení souboru z archivu ZIP ZipArchive.GetEntry
Načtení všech souborů z archivu zip ZipArchive.Entries
Otevření datového proudu do jednoho souboru obsaženého v archivu ZIP ZipArchiveEntry.Open
Odstranění souboru z archivu zip ZipArchiveEntry.Delete

Když vytvoříte novou položku, soubor se zkomprimuje a přidá do balíčku ZIP. Metoda CreateEntry umožňuje určit hierarchii adresáře při přidávání položky. Do balíčku ZIP zahrnete relativní cestu k nové položce. Například vytvoření nové položky s relativní cestou AddedFolder\NewFile.txt vytvoří komprimovaný textový soubor v adresáři s názvem AddedFolder.

Pokud odkazujete na System.IO.Compression.FileSystem sestavení v projektu, máte přístup ke čtyřem rozšiřujícím metodám (z ZipFileExtensions třídy) pro ZipArchive třídu: CreateEntryFromFile(ZipArchive, String, String), CreateEntryFromFile(ZipArchive, String, String, CompressionLevel), ExtractToDirectory(ZipArchive, String)a ExtractToDirectory(ZipArchive, String, Boolean) (k dispozici v .NET Core 2.0 a novějších verzích). Tyto rozšiřující metody umožňují komprimovat a dekompresi obsahu položky do souboru. Sestavení System.IO.Compression.FileSystem není k dispozici pro aplikace Windows 8.x Store. V aplikacích Windows 8.x Store můžete komprimovat a dekomprimovat soubory pomocí DeflateStream třídy nebo GZipStream pomocí prostředí Windows Runtime typů Compressor a Decompressor.

Příklady

První příklad ukazuje, jak vytvořit novou položku a zapisovat do ní pomocí streamu.

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

Následující příklad ukazuje, jak otevřít archiv zip a iterovat kolekci položek.

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

Třetí příklad ukazuje, jak pomocí rozšiřujících metod vytvořit novou položku v archivu ZIP z existujícího souboru a extrahovat obsah archivu. Pro spuštění kódu je nutné odkazovat System.IO.Compression.FileSystem na sestavení.

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

Konstruktory

ZipArchive(Stream)

Inicializuje novou instanci ZipArchive třídy ze zadaného datového proudu.

ZipArchive(Stream, ZipArchiveMode)

Inicializuje novou instanci ZipArchive třídy ze zadaného datového proudu a v zadaném režimu.

ZipArchive(Stream, ZipArchiveMode, Boolean)

Inicializuje novou instanci ZipArchive třídy v zadaném datovém proudu pro zadaný režim a volitelně ponechá datový proud otevřený.

ZipArchive(Stream, ZipArchiveMode, Boolean, Encoding)

Inicializuje novou instanci ZipArchive třídy v zadaném streamu pro zadaný režim, použije zadané kódování pro názvy položek a volitelně ponechá datový proud otevřený.

Vlastnosti

Comment

Získá nebo nastaví volitelný archivní komentář.

Entries

Získá kolekci položek, které jsou aktuálně v archivu zip.

Mode

Získá hodnotu, která popisuje typ akce zip archiv může provést položky.

Metody

CreateEntry(String)

Vytvoří prázdnou položku, která má zadanou cestu a název položky v archivu ZIP.

CreateEntry(String, CompressionLevel)

Vytvoří prázdnou položku, která má zadaný název položky a úroveň komprese v archivu zip.

Dispose()

Uvolní prostředky používané aktuální instancí třídy ZipArchive.

Dispose(Boolean)

Volá metodou Dispose() a Finalize() k uvolnění nespravovaných prostředků používaných aktuální instancí ZipArchive třídy a volitelně dokončí zápis archivu a uvolní spravované prostředky.

Equals(Object)

Určí, zda se zadaný objekt rovná aktuálnímu objektu.

(Zděděno od Object)
GetEntry(String)

Načte obálku pro zadanou položku v archivu zip.

GetHashCode()

Slouží jako výchozí hashovací funkce.

(Zděděno od Object)
GetType()

Získá aktuální Type instanci.

(Zděděno od Object)
MemberwiseClone()

Vytvoří mělkou kopii aktuálního Objectsouboru .

(Zděděno od Object)
ToString()

Vrátí řetězec, který představuje aktuální objekt.

(Zděděno od Object)

Metody rozšíření

CreateEntryFromFile(ZipArchive, String, String)

Archivuje soubor tak, že ho komprimuje a přidá do archivu zip.

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

Archivuje soubor tak, že ho komprimuje pomocí zadané úrovně komprese a přidá ho do archivu zip.

ExtractToDirectory(ZipArchive, String)

Extrahuje všechny soubory v archivu zip do adresáře v systému souborů.

ExtractToDirectory(ZipArchive, String, Boolean)

Extrahuje všechny soubory v archivu do adresáře v systému souborů.

Platí pro

Viz také