ZipArchive 클래스

정의

zip 보관 파일 형식으로 압축된 파일 패키지를 나타냅니다.

public ref class ZipArchive : IDisposable
public class ZipArchive : IDisposable
type ZipArchive = class
    interface IDisposable
Public Class ZipArchive
Implements IDisposable
상속
ZipArchive
구현

설명

zip 보관 파일 및 해당 파일 항목을 조작하는 메서드는 세 가지 클래스, 즉 , ZipArchiveZipArchiveEntry세 가지 ZipFile클래스에 분산됩니다.

대상 기능
디렉터리에서 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 네 가지 CreateEntryFromFile(ZipArchive, String, String)확장 메서드(클래스에서ZipFileExtensions)에 액세스할 수 있습니다. , CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)ExtractToDirectory(ZipArchive, String)ExtractToDirectory(ZipArchive, String, Boolean) (.NET Core 2.0 이상 버전에서 사용 가능). 이러한 확장 메서드를 사용하면 항목의 내용을 파일로 압축하고 압축 해제할 수 있습니다. System.IO.Compression.FileSystem Windows 8.x 스토어 앱에는 어셈블리를 사용할 수 없습니다. Windows 8.x 스토어 앱에서는 또는 클래스를 사용하여 DeflateStream 파일을 압축하고 압축을 풀거나 GZipStream Windows 런타임 형식 CompressorDecompressor사용할 수 있습니다.

예제

첫 번째 예제에서는 스트림을 사용하여 새 항목을 만들고 해당 항목에 쓰는 방법을 보여 있습니다.

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 메서드에 의해 호출되며 선택적으로 보관 파일을 작성하고 관리되는 리소스를 해제합니다.

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)

보관 파일의 모든 파일을 파일 시스템의 디렉터리에 추출합니다.

적용 대상

추가 정보