ZipFileExtensions ZipFileExtensions ZipFileExtensions ZipFileExtensions Class

Definición

Proporciona métodos de extensión para las clases ZipArchive y ZipArchiveEntry.Provides extension methods for the ZipArchive and ZipArchiveEntry classes.

public ref class ZipFileExtensions abstract sealed
public static class ZipFileExtensions
type ZipFileExtensions = class
Public Module ZipFileExtensions
Herencia
ZipFileExtensionsZipFileExtensionsZipFileExtensionsZipFileExtensions

Ejemplos

El ejemplo siguiente muestra cómo crear una nueva entrada en un archivo zip desde un archivo existente y extraiga el contenido del archivo en un directorio.The following example shows how to create a new entry in a zip archive from an existing file, and extract the contents of the archive to a directory.

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

El ejemplo siguiente muestra cómo recorrer en iteración el contenido de un archivo zip y extraer los archivos que tienen una extensión. txt.The following example shows how to iterate through the contents of a zip archive 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

Comentarios

El ZipFileExtensions clase solo contiene métodos estáticos que amplían el ZipArchive y ZipArchiveEntry clases.The ZipFileExtensions class contains only static methods that extend the ZipArchive and ZipArchiveEntry classes. No se cree una instancia de la ZipFileExtensions clase; en su lugar, usar estos métodos de las instancias de ZipArchive o ZipArchiveEntry.You do not create an instance of the ZipFileExtensions class; instead, you use these methods from instances of ZipArchive or ZipArchiveEntry.

Para usar los métodos de extensión, debe hacer referencia a la System.IO.Compression.FileSystem ensamblado del proyecto.To use the extension methods, you must reference the System.IO.Compression.FileSystem assembly in your project. El System.IO.Compression.FileSystem no está disponible en el ensamblado Tienda Windows 8.xWindows 8.x Store aplicaciones.The System.IO.Compression.FileSystem assembly is not available in Tienda Windows 8.xWindows 8.x Store apps. Por lo tanto, el ZipFileExtensions y ZipFile clases (ambos están en el System.IO.Compression.FileSystem ensamblado) no están disponibles en Tienda Windows 8.xWindows 8.x Store aplicaciones.Therefore, the ZipFileExtensions and ZipFile classes (both of which are in the System.IO.Compression.FileSystem assembly) are not available in Tienda Windows 8.xWindows 8.x Store apps. En Tienda Windows 8.xWindows 8.x Store aplicaciones, trabajar con archivos comprimidos mediante el uso de los métodos de ZipArchive, ZipArchiveEntry, DeflateStream, y GZipStream.In Tienda Windows 8.xWindows 8.x Store apps, you work with compressed files by using the methods in ZipArchive, ZipArchiveEntry, DeflateStream, and GZipStream.

El ZipFileExtensions clase contiene tres métodos que extienden ZipArchive:The ZipFileExtensions class contains three methods that extend ZipArchive:

El ZipFileExtensions clase contiene dos métodos que extienden ZipArchiveEntry:The ZipFileExtensions class contains two methods that extend ZipArchiveEntry:

Métodos

CreateEntryFromFile(ZipArchive, String, String) CreateEntryFromFile(ZipArchive, String, String) CreateEntryFromFile(ZipArchive, String, String) CreateEntryFromFile(ZipArchive, String, String)

Archiva un archivo comprimiéndolo y agregándolo al archivo zip.Archives a file by compressing it and adding it to the zip archive.

CreateEntryFromFile(ZipArchive, String, String, CompressionLevel) CreateEntryFromFile(ZipArchive, String, String, CompressionLevel) CreateEntryFromFile(ZipArchive, String, String, CompressionLevel) CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)

Archiva un archivo comprimiéndolo mediante el nivel especificado de compresión y agregándolo al archivo zip.Archives a file by compressing it using the specified compression level and adding it to the zip archive.

ExtractToDirectory(ZipArchive, String) ExtractToDirectory(ZipArchive, String) ExtractToDirectory(ZipArchive, String) ExtractToDirectory(ZipArchive, String)

Extrae todos los archivos del archivo zip a un directorio del sistema de archivos.Extracts all the files in the zip archive to a directory on the file system.

ExtractToDirectory(ZipArchive, String, Boolean) ExtractToDirectory(ZipArchive, String, Boolean) ExtractToDirectory(ZipArchive, String, Boolean) ExtractToDirectory(ZipArchive, String, Boolean)
ExtractToFile(ZipArchiveEntry, String) ExtractToFile(ZipArchiveEntry, String) ExtractToFile(ZipArchiveEntry, String) ExtractToFile(ZipArchiveEntry, String)

Dibuja una entrada del archivo zip a un archivo.Extracts an entry in the zip archive to a file.

ExtractToFile(ZipArchiveEntry, String, Boolean) ExtractToFile(ZipArchiveEntry, String, Boolean) ExtractToFile(ZipArchiveEntry, String, Boolean) ExtractToFile(ZipArchiveEntry, String, Boolean)

Extrae una entrada del archivo zip a un archivo, y sobrescribe opcionalmente un archivo existente que tiene el mismo nombre.Extracts an entry in the zip archive to a file, and optionally overwrites an existing file that has the same name.

Se aplica a