使用SharpZipLib解压缩特定文件?

时间:2008-11-30 02:05:48

标签: .net compression sharpziplib

我正在尝试使用SharpZipLib从zip存档中提取指定的文件。我见过的所有例子总是希望你能解压缩整个拉链,并按照以下方式做一些事情:

       FileStream fileStreamIn = new FileStream (sourcePath, FileMode.Open, FileAccess.Read);

        ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
        ZipEntry entry;

        while (entry = zipInStream.GetNextEntry() != null)
        {
            // Unzip file
        }

我想做的是:

ZipEntry entry = zipInStream.SeekToFile("FileName");

由于我的需求涉及使用zip作为包,并且只根据需要将文件抓取到内存中。

有人熟悉SharpZipLib吗?有没有人知道我是否可以手动完成整个拉链?

4 个答案:

答案 0 :(得分:42)

ZipFile.GetEntry应该这样做:

using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
using (var zf = new ZipFile(fs)) {
   var ze = zf.GetEntry(fileName);
   if (ze == null) {
      throw new ArgumentException(fileName, "not found in Zip");
   }

   using (var s = zf.GetInputStream(ze)) {
      // do something with ZipInputStream
   }
}

答案 1 :(得分:15)

FastZip.ExtractZip (string zipFileName, string targetDirectory, string fileFilter)

可以根据文件过滤器(即常规表达字符串)提取一个或多个文件

以下是有关文件过滤器的文档:

// A filter is a sequence of independant <see cref="Regex">regular expressions</see> separated by semi-colons ';'
// Each expression can be prefixed by a plus '+' sign or a minus '-' sign to denote the expression
// is intended to include or exclude names.  If neither a plus or minus sign is found include is the default
// A given name is tested for inclusion before checking exclusions.  Only names matching an include spec
// and not matching an exclude spec are deemed to match the filter.
// An empty filter matches any name.
// </summary>
// <example>The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
// "+\.dat$;-^dummy\.dat$"

因此,对于名为myfile.dat的文件,您可以使用“+。* myfile \ .dat $”作为文件过滤器。

答案 2 :(得分:6)

DotNetZip在ZipFile类上有一个字符串索引器,可以让它变得非常简单。

 using (ZipFile zip = ZipFile.Read(sourcePath)
 {
   zip["NameOfFileToUnzip.txt"].Extract();
 }

您不需要调整输入流和输出流等,只需提取文件即可。另一方面,如果你想要流,你可以得到它:

 using (ZipFile zip = ZipFile.Read(sourcePath)
 {
   Stream s = zip["NameOfFileToUnzip.txt"].OpenReader();
   // fiddle with stream here
 }

您也可以进行通配符提取。

 using (ZipFile zip = ZipFile.Read(sourcePath)
 {
     // extract all XML files in the archive
     zip.ExtractSelectedEntries("*.xml");
 }

指定覆盖/不覆盖,不同的目标目录等都有重载。您还可以根据文件名以外的条件进行提取。例如,提取比2009年1月15日更新的所有文件:

     // extract all files modified after 15 Jan 2009
     zip.ExtractSelectedEntries("mtime > 2009-01-15");

你可以结合标准:

     // extract all files that are modified after 15 Jan 2009) AND  larger than 1mb
     zip.ExtractSelectedEntries("mtime > 2009-01-15 and size > 1mb");

     // extract all XML files that are modified after 15 Jan 2009) AND  larger than 1mb
     zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15 and size > 1mb");

您不必提取您选择的文件。您可以选择它们,然后决定是否提取。

    using (ZipFile zip1 = ZipFile.Read(ZipFileName))
    {
        var PhotoShopFiles = zip1.SelectEntries("*.psd");
        // the selection is just an ICollection<ZipEntry>
        foreach (ZipEntry e in PhotoShopFiles)
        {
            // examine metadata here, make decision on extraction
            e.Extract();
        }
    }

答案 3 :(得分:2)

我可以选择VB.NET,从Zip存档器中提取特定文件。西班牙语评论。获取Zip文件路径,要提取的文件名,密码(如果需要)。如果OriginalPath设置为1,则提取到原始路径;如果OriginalPath = 0,则使用DestPath。密切关注“ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream”的内容......

如下:

''' <summary>
''' Extrae un archivo específico comprimido dentro de un archivo zip
''' </summary>
''' <param name="SourceZipPath"></param>
''' <param name="FileName">Nombre del archivo buscado. Debe incluir ruta, si se comprimió usando guardar con FullPath</param>
''' <param name="DestPath">Ruta de destino del archivo. Ver parámetro OriginalPath.</param>
''' <param name="password">Si el archivador no tiene contraseña, puede quedar en blanco</param>
''' <param name="OriginalPath">OriginalPath=1, extraer en la RUTA ORIGINAL. OriginalPath=0, extraer en DestPath</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ExtractSpecificZipFile(ByVal SourceZipPath As String, ByVal FileName As String, _
ByVal DestPath As String, ByVal password As String, ByVal OriginalPath As Integer) As Boolean
    Try
        Dim fileStreamIn As FileStream = New FileStream(SourceZipPath, FileMode.Open, FileAccess.Read)
        Dim fileStreamOut As FileStream
        Dim zf As ZipFile = New ZipFile(fileStreamIn)

        Dim Size As Integer
        Dim buffer(4096) As Byte

        zf.Password = password

        Dim Zentry As ZipEntry = zf.GetEntry(FileName)

        If (Zentry Is Nothing) Then
            Debug.Print("not found in Zip")
            Return False
            Exit Function
        End If

        Dim fstr As ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream
        fstr = zf.GetInputStream(Zentry)

        If OriginalPath = 1 Then
            Dim strFullPath As String = Path.GetDirectoryName(Zentry.Name)
            Directory.CreateDirectory(strFullPath)
            fileStreamOut = New FileStream(strFullPath & "\" & Path.GetFileName(Zentry.Name), FileMode.Create, FileAccess.Write)
        Else
            fileStreamOut = New FileStream(DestPath + "\" + Path.GetFileName(Zentry.Name), FileMode.Create, FileAccess.Write)
        End If


        Do
            Size = fstr.Read(buffer, 0, buffer.Length)
            fileStreamOut.Write(buffer, 0, Size)
        Loop While (Size > 0)

        fstr.Close()
        fileStreamOut.Close()
        fileStreamIn.Close()
        Return True
    Catch ex As Exception
        Return False
    End Try

End Function