ZipArchive Sınıf

Tanım

Sıkıştırılmış dosyaların zip arşiv biçimindeki bir paketini temsil eder.

public ref class ZipArchive : IDisposable
public class ZipArchive : IDisposable
type ZipArchive = class
    interface IDisposable
Public Class ZipArchive
Implements IDisposable
Devralma
ZipArchive
Uygulamalar

Açıklamalar

Zip arşivlerini ve bunların dosya girdilerini düzenleme yöntemleri üç sınıfa yayılır: ZipFile, ZipArchiveve ZipArchiveEntry.

Amaç Kullanın
Dizinden zip arşivi oluşturma ZipFile.CreateFromDirectory
Zip arşivinin içeriğini dizine ayıklama ZipFile.ExtractToDirectory
Mevcut zip arşivine yeni dosyalar ekleme ZipArchive.CreateEntry
Zip arşivinden dosya alma ZipArchive.GetEntry
Zip arşivinden tüm dosyaları alma ZipArchive.Entries
Zip arşivinde bulunan tek bir dosyaya akış açma ZipArchiveEntry.Open
Zip arşivinden dosya silme ZipArchiveEntry.Delete

Yeni bir giriş oluşturduğunuzda dosya sıkıştırılır ve zip paketine eklenir. yöntemi, CreateEntry girişi eklerken bir dizin hiyerarşisi belirtmenizi sağlar. Yeni girdinin göreli yolunu zip paketine eklersiniz. Örneğin, göreli yolu AddedFolder\NewFile.txt olan yeni bir giriş oluşturmak, AddFolder adlı dizinde sıkıştırılmış bir metin dosyası oluşturur.

Projenizdeki derlemeye System.IO.Compression.FileSystem başvurursanız, sınıfı için ZipArchive dört uzantı yöntemine (sınıfındanZipFileExtensions) erişebilirsiniz: CreateEntryFromFile(ZipArchive, String, String), CreateEntryFromFile(ZipArchive, String, String, CompressionLevel), ExtractToDirectory(ZipArchive, String)ve ExtractToDirectory(ZipArchive, String, Boolean) (.NET Core 2.0 ve sonraki sürümlerde kullanılabilir). Bu uzantı yöntemleri, bir dosyaya girişin içeriğini sıkıştırmanızı ve açmanızı sağlar. Derleme System.IO.Compression.FileSystem Windows 8.x Store uygulamalarında kullanılamaz. Windows 8.x Store uygulamalarında, veya GZipStream sınıfını DeflateStream kullanarak dosyaları sıkıştırabilir ve açabilir veya ve Windows Çalışma Zamanı türlerini Compressor Decompressorkullanabilirsiniz.

Örnekler

İlk örnekte yeni bir girdi oluşturma ve akış kullanarak bu girişe yazma işlemi gösterilmektedir.

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

Aşağıdaki örnek, bir zip arşivini açmayı ve girdi koleksiyonunda yinelemeyi gösterir.

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

Üçüncü örnekte, mevcut bir dosyadan zip arşivinde yeni bir giriş oluşturmak ve arşiv içeriğini ayıklamak için uzantı yöntemlerinin nasıl kullanılacağı gösterilmektedir. Kodu yürütmek için derlemeye başvurmanız System.IO.Compression.FileSystem gerekir.

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

Oluşturucular

ZipArchive(Stream)

Belirtilen akıştan sınıfının yeni bir örneğini ZipArchive başlatır.

ZipArchive(Stream, ZipArchiveMode)

Belirtilen akıştan ve belirtilen modla sınıfının yeni bir örneğini ZipArchive başlatır.

ZipArchive(Stream, ZipArchiveMode, Boolean)

Belirtilen mod için belirtilen akışta sınıfının yeni bir örneğini ZipArchive başlatır ve isteğe bağlı olarak akışı açık bırakır.

ZipArchive(Stream, ZipArchiveMode, Boolean, Encoding)

Belirtilen mod için belirtilen akışta sınıfının yeni bir örneğini ZipArchive başlatır, girdi adları için belirtilen kodlamayı kullanır ve isteğe bağlı olarak akışı açık bırakır.

Özellikler

Comment

İsteğe bağlı arşiv açıklamasını alır veya ayarlar.

Entries

Şu anda zip arşivinde olan girdilerin koleksiyonunu alır.

Mode

Zip arşivinin girdilerde gerçekleştirebileceği eylemin türünü açıklayan bir değer alır.

Yöntemler

CreateEntry(String)

Zip arşivinde belirtilen yola ve giriş adına sahip boş bir giriş oluşturur.

CreateEntry(String, CompressionLevel)

Zip arşivinde belirtilen giriş adına ve sıkıştırma düzeyine sahip boş bir giriş oluşturur.

Dispose()

ZipArchive sınıfının geçerli örneği tarafından kullanılan kaynakları serbest bırakır.

Dispose(Boolean)

sınıfının geçerli örneği ZipArchive tarafından kullanılan yönetilmeyen kaynakları serbest bırakmak için ve Finalize() yöntemleri tarafından Dispose() çağrılır ve isteğe bağlı olarak arşivi yazmayı tamamlar ve yönetilen kaynakları serbest bırakır.

Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.

(Devralındığı yer: Object)
GetEntry(String)

Zip arşivinde belirtilen giriş için bir sarmalayıcı alır.

GetHashCode()

Varsayılan karma işlevi işlevi görür.

(Devralındığı yer: Object)
GetType()

Type Geçerli örneğini alır.

(Devralındığı yer: Object)
MemberwiseClone()

Geçerli Objectöğesinin sığ bir kopyasını oluşturur.

(Devralındığı yer: Object)
ToString()

Geçerli nesneyi temsil eden dizeyi döndürür.

(Devralındığı yer: Object)

Uzantı Metotları

CreateEntryFromFile(ZipArchive, String, String)

Dosyayı sıkıştırıp zip arşivine ekleyerek arşivler.

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

Bir dosyayı belirtilen sıkıştırma düzeyini kullanarak sıkıştırarak ve zip arşivine ekleyerek arşivler.

ExtractToDirectory(ZipArchive, String)

Zip arşivindeki tüm dosyaları dosya sistemindeki bir dizine ayıklar.

ExtractToDirectory(ZipArchive, String, Boolean)

Arşivdeki tüm dosyaları dosya sistemindeki bir dizine ayıklar.

Şunlara uygulanır

Ayrıca bkz.