ZipArchiveEntry Класс

Определение

Представляет сжатый файл внутри ZIP-архива.

public ref class ZipArchiveEntry
public class ZipArchiveEntry
type ZipArchiveEntry = class
Public Class ZipArchiveEntry
Наследование
ZipArchiveEntry

Комментарии

ZIP-архив содержит запись для каждого сжатого файла. Класс ZipArchiveEntry позволяет проверить свойства записи, а также открыть или удалить запись. Открыв запись, вы можете изменить сжатый файл, записав в поток для этого сжатого файла.

Методы управления ZIP-архивами и их записями файлов распределены по трем классам: ZipFileи ZipArchiveEntryZipArchive .

Кому... Используйте...
Создание ZIP-архива из каталога ZipFile.CreateFromDirectory
Извлечение содержимого ZIP-архива в каталог ZipFile.ExtractToDirectory
Добавление новых файлов в существующий ZIP-архив ZipArchive.CreateEntry
Получение файла в ZIP-архиве ZipArchive.GetEntry
Получение всех файлов в ZIP-архиве ZipArchive.Entries
Открытие потока в отдельный файл, содержащийся в ZIP-архиве ZipArchiveEntry.Open
Удаление файла из ZIP-архива ZipArchiveEntry.Delete

Если вы ссылаетесь на сборку System.IO.Compression.FileSystem в проекте, вы можете получить доступ к двум методам расширения для ZipArchiveEntry класса . Это методы ExtractToFile(ZipArchiveEntry, String) и ExtractToFile(ZipArchiveEntry, String, Boolean), которые позволяют распаковывать содержимое записи в файл. Сборка System.IO.Compression.FileSystem недоступна в Windows 8. В приложениях магазина Windows 8.x можно распаковывать содержимое архива с помощью DeflateStream или GZipStreamили использовать типы Compressor среда выполнения Windows и Decompressor для сжатия и распаковки файлов.

Примеры

В первом примере показано, как создать новую запись в ZIP-архиве и выполнить запись в нее.

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

Во втором примере показано, как использовать ExtractToFile(ZipArchiveEntry, String) метод расширения. Для выполнения кода необходимо ссылаться на System.IO.Compression.FileSystem сборку в проекте.

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

Свойства

Archive

Получает ZIP-архив, к которому принадлежит запись.

Comment

Возвращает или задает необязательный комментарий к записи.

CompressedLength

Получает сжатый размер записи в ZIP-архиве.

Crc32

32-разрядная циклическая избыточная проверка.

ExternalAttributes

Атрибуты файла, зависящие от операционной системы и приложения.

FullName

Получает относительный путь записи в ZIP-архиве.

IsEncrypted

Возвращает значение, указывающее, зашифрована ли запись.

LastWriteTime

Получает или задает время последнего изменения записи в ZIP-архиве.

Length

Получает несжатый размер записи в ZIP-архиве.

Name

Получает имя файла записи в ZIP-архиве.

Методы

Delete()

Удаляет запись из ZIP-архива.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Open()

Открывает запись из ZIP-архива.

ToString()

Извлекает относительный путь записи в ZIP-архиве.

Методы расширения

ExtractToFile(ZipArchiveEntry, String)

Извлекает запись в ZIP-архиве в файл.

ExtractToFile(ZipArchiveEntry, String, Boolean)

Извлекает запись из ZIP-архива в файл и при необходимости перезаписывает существующий файл с тем же именем.

Применяется к