ZipFileExtensions.ExtractToFile 메서드

정의

ZIP 보관 파일의 항목을 파일에 추출합니다.

오버로드

ExtractToFile(ZipArchiveEntry, String)

ZIP 보관 파일의 항목을 파일에 추출합니다.

ExtractToFile(ZipArchiveEntry, String, Boolean)

zip 보관 항목을 파일로 추출하고 필요에 따라 동일한 이름을 가진 기존 파일을 덮어씁니다.

ExtractToFile(ZipArchiveEntry, String)

Source:
ZipFileExtensions.ZipArchiveEntry.Extract.cs
Source:
ZipFileExtensions.ZipArchiveEntry.Extract.cs
Source:
ZipFileExtensions.ZipArchiveEntry.Extract.cs

ZIP 보관 파일의 항목을 파일에 추출합니다.

public:
[System::Runtime::CompilerServices::Extension]
 static void ExtractToFile(System::IO::Compression::ZipArchiveEntry ^ source, System::String ^ destinationFileName);
public static void ExtractToFile (this System.IO.Compression.ZipArchiveEntry source, string destinationFileName);
static member ExtractToFile : System.IO.Compression.ZipArchiveEntry * string -> unit
<Extension()>
Public Sub ExtractToFile (source As ZipArchiveEntry, destinationFileName As String)

매개 변수

source
ZipArchiveEntry

파일을 추출하는 zip 보관 항목입니다.

destinationFileName
String

항목의 내용에서 만들 파일의 경로입니다. 상대 경로 또는 절대 경로를 지정할 수 있습니다. 상대 경로는 현재 작업 디렉터리에 상대적으로 해석됩니다.

예외

destinationFileName가 빈 문자열이거나 공백만 포함하거나 InvalidPathChars로 정의된 하나 이상의 잘못된 문자를 포함합니다.

또는

destinationFileName은 디렉터리를 지정합니다.

destinationFileName이(가) null인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

destinationFileName가 이미 있는 경우

또는

I/O 오류가 발생했습니다.

또는

엔트리가 현재 쓰기용으로 열려 있습니다.

또는

엔트리가 보관 저장소에서 삭제되었습니다.

호출자에게 새 파일을 만드는 데 필요한 권한이 없습니다.

항목이 보관 위치에 없거나 손상되어 열 수 없습니다.

또는

항목이 지원되지 않는 압축 방법으로 압축되었습니다.

이 항목이 속하는 zip 보관 위치가 삭제되었습니다.

destinationFileName의 형식이 잘못되었습니다.

또는

이 항목에 대한 zip 보관 파일을 Create 모드에서 열었으며 이는 항목 검색을 허용하지 않습니다.

예제

다음 예제에서는 zip 보관 파일의 내용을 반복하고 확장명이 .txt 파일을 추출하는 방법을 보여 줍니다.

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

설명

대상 파일이 이미 있는 경우 이 메서드는 덮어쓰지 않습니다. 예외를 throw합니다 IOException . 기존 파일을 덮어쓰려면 메서드 오버로드를 ExtractToFile(ZipArchiveEntry, String, Boolean) 대신 사용합니다.

파일의 마지막 쓰기 시간은 zip 보관 파일의 항목이 마지막으로 변경된 시간으로 설정됩니다. 이 값은 속성에 LastWriteTime 저장됩니다.

이 메서드를 사용하여 디렉터리를 추출할 수 없습니다. 대신 메서드를 ExtractToDirectory 사용합니다.

적용 대상

ExtractToFile(ZipArchiveEntry, String, Boolean)

Source:
ZipFileExtensions.ZipArchiveEntry.Extract.cs
Source:
ZipFileExtensions.ZipArchiveEntry.Extract.cs
Source:
ZipFileExtensions.ZipArchiveEntry.Extract.cs

zip 보관 항목을 파일로 추출하고 필요에 따라 동일한 이름을 가진 기존 파일을 덮어씁니다.

public:
[System::Runtime::CompilerServices::Extension]
 static void ExtractToFile(System::IO::Compression::ZipArchiveEntry ^ source, System::String ^ destinationFileName, bool overwrite);
public static void ExtractToFile (this System.IO.Compression.ZipArchiveEntry source, string destinationFileName, bool overwrite);
static member ExtractToFile : System.IO.Compression.ZipArchiveEntry * string * bool -> unit
<Extension()>
Public Sub ExtractToFile (source As ZipArchiveEntry, destinationFileName As String, overwrite As Boolean)

매개 변수

source
ZipArchiveEntry

파일을 추출하는 zip 보관 항목입니다.

destinationFileName
String

항목의 내용에서 만들 파일의 경로입니다. 상대 경로 또는 절대 경로를 지정할 수 있습니다. 상대 경로는 현재 작업 디렉터리에 상대적으로 해석됩니다.

overwrite
Boolean

대상 파일과 동일한 이름의 기존 파일을 덮어쓰려면true 이고, 그렇지 않으면 false입니다.

예외

destinationFileName가 빈 문자열이거나 공백만 포함하거나 InvalidPathChars로 정의된 하나 이상의 잘못된 문자를 포함합니다.

또는

destinationFileName은 디렉터리를 지정합니다.

destinationFileName이(가) null인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

destinationFileName 이 이미 있고 overwritefalse입니다.

또는

I/O 오류가 발생했습니다.

또는

엔트리가 현재 쓰기용으로 열려 있습니다.

또는

엔트리가 보관 저장소에서 삭제되었습니다.

호출자에게 새 파일을 만드는 데 필요한 권한이 없습니다.

항목이 보관 위치에 없거나 손상되어 열 수 없습니다.

또는

항목이 지원되지 않는 압축 방법으로 압축되었습니다.

이 항목이 속하는 zip 보관 위치가 삭제되었습니다.

destinationFileName의 형식이 잘못되었습니다.

또는

이 항목에 대한 zip 보관 파일을 Create 모드에서 열었으며 이는 항목 검색을 허용하지 않습니다.

예제

다음 예제에서는 zip 보관 파일의 내용을 반복하고 확장명이 .txt 파일을 추출하는 방법을 보여 줍니다. 대상 폴더에 이름이 같은 기존 파일을 덮어씁니다. 이 코드 예제를 컴파일하려면 프로젝트의 및 System.IO.Compression.FileSystem 어셈블리를 System.IO.Compression 참조해야 합니다.

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string zipPath = @"c:\example\start.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))
                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, true);
                    }
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Module Module1

    Sub Main()
        Dim zipPath As String = "c:\example\start.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) 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, true)
                    End If

                End If
            Next
        End Using
    End Sub

End Module

설명

파일의 마지막 쓰기 시간은 zip 보관 파일의 항목이 마지막으로 변경된 시간으로 설정됩니다. 이 값은 속성에 LastWriteTime 저장됩니다.

이 메서드를 사용하여 디렉터리를 추출할 수 없습니다. 대신 메서드를 ExtractToDirectory 사용합니다.

적용 대상