ZipFileExtensions.ExtractToFile 方法

定义

将 zip 存档中的条目解压到文件下。Extracts an entry in the zip archive to a file.

重载

ExtractToFile(ZipArchiveEntry, String)

将 zip 存档中的条目解压到文件下。Extracts an entry in the zip archive to a file.

ExtractToFile(ZipArchiveEntry, String, Boolean)

将 zip 存档中的条目解压缩到文件下,并可选择覆盖具有相同名称的现有文件。Extracts an entry in the zip archive to a file, and optionally overwrites an existing file that has the same name.

ExtractToFile(ZipArchiveEntry, String)

将 zip 存档中的条目解压到文件下。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)

参数

source
ZipArchiveEntry

要从其中解压缩文件的 zip 存档条目。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.

例外

destinationFileName 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。destinationFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

- 或 --or- destinationFileName 指定目录。destinationFileName specifies a directory.

destinationFileNamenulldestinationFileName 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 已存在。destinationFileName already exists.

- 或 --or- 出现 I/O 错误。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.

已释放该条目所属的 zip 存档。The zip archive that this entry belongs to has been disposed.

destinationFileName 的格式无效。destinationFileName is in an invalid format.

- 或 --or- 该条目的 zip 存档是在 Create 模式中打开的,不允许检索条目。The zip archive for this entry was opened in Create mode, which does not permit the retrieval of entries.

示例

下面的示例演示如何遍历 zip 存档文件的内容,并提取扩展名为 .txt 的文件。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

注解

如果目标文件已存在,则此方法不会覆盖它;它会引发 IOException 异常。If the destination file already exists, this method does not overwrite it; it throws an IOException exception. 若要覆盖现有文件,请改为使用 ExtractToFile(ZipArchiveEntry, String, Boolean) 方法重载。To overwrite an existing file, use the ExtractToFile(ZipArchiveEntry, String, Boolean) method overload instead.

文件的上次写入时间被设置为最后一次更改 zip 存档中的条目的时间;此值存储在属性中 LastWriteTimeThe 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.

不能使用此方法提取目录;请改用 ExtractToDirectory 方法。You cannot use this method to extract a directory; use the ExtractToDirectory method instead.

适用于

ExtractToFile(ZipArchiveEntry, String, Boolean)

将 zip 存档中的条目解压缩到文件下,并可选择覆盖具有相同名称的现有文件。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)

参数

source
ZipArchiveEntry

要从其中解压缩文件的 zip 存档条目。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;否则为 falsetrue to overwrite an existing file that has the same name as the destination file; otherwise, false.

例外

destinationFileName 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。destinationFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

- 或 --or- destinationFileName 指定目录。destinationFileName specifies a directory.

destinationFileNamenulldestinationFileName 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 已存在,且 overwritefalsedestinationFileName already exists and overwrite is false.

- 或 --or- 出现 I/O 错误。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.

已释放该条目所属的 zip 存档。The zip archive that this entry belongs to has been disposed.

destinationFileName 的格式无效。destinationFileName is in an invalid format.

- 或 --or- 该条目的 zip 存档是在 Create 模式中打开的,不允许检索条目。The zip archive for this entry was opened in Create mode, which does not permit the retrieval of entries.

示例

下面的示例演示如何遍历 zip 存档文件的内容,并提取扩展名为 .txt 的文件。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. 若要编译器此代码示例,必须 System.IO.Compression System.IO.Compression.FileSystem 在项目中引用和程序集。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

注解

文件的上次写入时间被设置为最后一次更改 zip 存档中的条目的时间;此值存储在属性中 LastWriteTimeThe 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.

不能使用此方法提取目录;请改用 ExtractToDirectory 方法。You cannot use this method to extract a directory; use the ExtractToDirectory method instead.

适用于