Editare

Partajați prin


ZipFileExtensions.ExtractToFile Method

Definition

Extracts an entry in the zip archive to a file.

Overloads

ExtractToFile(ZipArchiveEntry, String)

Extracts an entry in the zip archive to a file.

ExtractToFile(ZipArchiveEntry, String, Boolean)

Extracts an entry in the zip archive to a file, and optionally overwrites an existing file that has the same name.

ExtractToFile(ZipArchiveEntry, String)

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

Extracts an entry in the zip archive to a file.

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)

Parameters

source
ZipArchiveEntry

The zip archive entry to extract a file from.

destinationFileName
String

The path of the file to create from the contents of the entry. You can specify either a relative or an absolute path. A relative path is interpreted as relative to the current working directory.

Exceptions

destinationFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

-or-

destinationFileName specifies a directory.

destinationFileName is null.

The specified path, file name, or both exceed the system-defined maximum length.

The specified path is invalid (for example, it is on an unmapped drive).

destinationFileName already exists.

-or-

An I/O error occurred.

-or-

The entry is currently open for writing.

-or-

The entry has been deleted from the archive.

The caller does not have the required permission to create the new file.

The entry is missing from the archive, or is corrupt and cannot be read.

-or-

The entry has been compressed by using a compression method that is not supported.

The zip archive that this entry belongs to has been disposed.

destinationFileName is in an invalid format.

-or-

The zip archive for this entry was opened in Create mode, which does not permit the retrieval of entries.

Examples

The following example shows how to iterate through the contents of a zip archive file and extract files that have a .txt extension.

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

Remarks

If the destination file already exists, this method does not overwrite it; it throws an IOException exception. To overwrite an existing file, use the ExtractToFile(ZipArchiveEntry, String, Boolean) method overload instead.

The last write time of the file is set to the last time the entry in the zip archive was changed; this value is stored in the LastWriteTime property.

You cannot use this method to extract a directory; use the ExtractToDirectory method instead.

Applies to

ExtractToFile(ZipArchiveEntry, String, Boolean)

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

Extracts an entry in the zip archive to a file, and optionally overwrites an existing file that has the same name.

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)

Parameters

source
ZipArchiveEntry

The zip archive entry to extract a file from.

destinationFileName
String

The path of the file to create from the contents of the entry. You can specify either a relative or an absolute path. A relative path is interpreted as relative to the current working directory.

overwrite
Boolean

true to overwrite an existing file that has the same name as the destination file; otherwise, false.

Exceptions

destinationFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

-or-

destinationFileName specifies a directory.

destinationFileName is null.

The specified path, file name, or both exceed the system-defined maximum length.

The specified path is invalid (for example, it is on an unmapped drive).

destinationFileName already exists and overwrite is false.

-or-

An I/O error occurred.

-or-

The entry is currently open for writing.

-or-

The entry has been deleted from the archive.

The caller does not have the required permission to create the new file.

The entry is missing from the archive or is corrupt and cannot be read.

-or-

The entry has been compressed by using a compression method that is not supported.

The zip archive that this entry belongs to has been disposed.

destinationFileName is in an invalid format.

-or-

The zip archive for this entry was opened in Create mode, which does not permit the retrieval of entries.

Examples

The following example shows how to iterate through the contents of a zip archive file, and extract files that have a .txt extension. It overwrites an existing file that has the same name in the destination folder. In order to compiler this code example, you must reference the System.IO.Compression and System.IO.Compression.FileSystem assemblies in your project.

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

Remarks

The last write time of the file is set to the last time the entry in the zip archive was changed; this value is stored in the LastWriteTime property.

You cannot use this method to extract a directory; use the ExtractToDirectory method instead.

Applies to