ZipFileExtensions.ExtractToFile Método

Definição

Extrai uma entrada do arquivo zip para um ficheiro.

Sobrecargas

Name Description
ExtractToFile(ZipArchiveEntry, String)

Extrai uma entrada do arquivo zip para um ficheiro.

ExtractToFile(ZipArchiveEntry, String, Boolean)

Extrai uma entrada no arquivo zip para um ficheiro e, opcionalmente, sobrescrive um ficheiro existente com o mesmo nome.

ExtractToFile(ZipArchiveEntry, String)

Extrai uma entrada do arquivo zip para um ficheiro.

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)

Parâmetros

source
ZipArchiveEntry

A entrada do arquivo zip para extrair um ficheiro.

destinationFileName
String

O caminho do ficheiro a ser criado a partir do conteúdo da entrada. Pode especificar um caminho relativo ou um caminho absoluto. Um caminho relativo é interpretado como relativo ao diretório de trabalho atual.

Exceções

destinationFileName é uma cadeia de comprimento zero, contém apenas espaços em branco, ou contém um ou mais caracteres inválidos conforme definido por InvalidPathChars.

-ou-

destinationFileName especifica um diretório.

destinationFileName é null.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado é inválido (por exemplo, está num disco não mapeado).

destinationFileName já existe.

-ou-

Ocorreu um erro de I/O.

-ou-

A entrada está atualmente aberta para escrita.

-ou-

A entrada foi apagada do arquivo.

O chamador não tem a permissão necessária para criar o novo ficheiro.

A entrada está em falta no arquivo, ou está corrompida e não pode ser lida.

-ou-

A entrada foi comprimida usando um método de compressão que não é suportado.

O arquivo postal a que esta entrada pertence foi descartado.

destinationFileName está num formato inválido.

-ou-

O arquivo postal desta entrada foi aberto no Create modo, que não permite a recuperação de entradas.

Exemplos

O exemplo seguinte mostra como iterar pelo conteúdo de um ficheiro zip e extrair ficheiros que têm uma extensão .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

Observações

Se o ficheiro de destino já existir, este método não o sobreescreve; Faz uma IOException exceção. Para sobrescrever um ficheiro existente, use o ExtractToFile(ZipArchiveEntry, String, Boolean) método overload em vez disso.

O último tempo de escrita do ficheiro é definido para a última vez que a entrada no arquivo zip foi alterada; este valor é armazenado na LastWriteTime propriedade.

Não pode usar este método para extrair um diretório; Usa o ExtractToDirectory método em vez disso.

Aplica-se a

ExtractToFile(ZipArchiveEntry, String, Boolean)

Extrai uma entrada no arquivo zip para um ficheiro e, opcionalmente, sobrescrive um ficheiro existente com o mesmo nome.

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)

Parâmetros

source
ZipArchiveEntry

A entrada do arquivo zip para extrair um ficheiro.

destinationFileName
String

O caminho do ficheiro a ser criado a partir do conteúdo da entrada. Pode especificar um caminho relativo ou um caminho absoluto. Um caminho relativo é interpretado como relativo ao diretório de trabalho atual.

overwrite
Boolean

true para sobrescrever um ficheiro existente que tenha o mesmo nome do ficheiro de destino; caso contrário, false.

Exceções

destinationFileName é uma cadeia de comprimento zero, contém apenas espaços em branco, ou contém um ou mais caracteres inválidos conforme definido por InvalidPathChars.

-ou-

destinationFileName especifica um diretório.

destinationFileName é null.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado é inválido (por exemplo, está num disco não mapeado).

destinationFileName já existe e overwrite é false.

-ou-

Ocorreu um erro de I/O.

-ou-

A entrada está atualmente aberta para escrita.

-ou-

A entrada foi apagada do arquivo.

O chamador não tem a permissão necessária para criar o novo ficheiro.

A entrada está em falta no arquivo ou está corrompida e não pode ser lida.

-ou-

A entrada foi comprimida usando um método de compressão que não é suportado.

O arquivo postal a que esta entrada pertence foi descartado.

destinationFileName está num formato inválido.

-ou-

O arquivo postal desta entrada foi aberto no Create modo, que não permite a recuperação de entradas.

Exemplos

O exemplo seguinte mostra como iterar pelo conteúdo de um ficheiro zip e extrair ficheiros que têm uma extensão .txt. Sobrescreve um ficheiro existente com o mesmo nome na pasta de destino. Para compilar este exemplo de código, deve referenciar os System.IO.Compression assemblies e System.IO.Compression.FileSystem no seu projeto.

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

Observações

O último tempo de escrita do ficheiro é definido para a última vez que a entrada no arquivo zip foi alterada; este valor é armazenado na LastWriteTime propriedade.

Não pode usar este método para extrair um diretório; Usa o ExtractToDirectory método em vez disso.

Aplica-se a