如何使用 SharpZipLib 解压某个具体文件?

.Net技术 码拜 10年前 (2015-07-02) 2168次浏览 0个评论

我试图用 sharpziplib 将指定的文件从ZIP存档解压。我找到的总是解压整个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的,有谁知道我该怎样做?

方案一:

用 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
   }
}
更多SharpZipLib示例参考 

I’m trying to use SharpZipLib to pull specified files from a zip archive. All of the examples I’ve seen always expect that you want to unzip the entire zip, and do something along the lines of:

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

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

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

What I want to do is something like:

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

As my needs involve using a zip as a package and only grabbing files into memory as needed.

Is anyone familiar with SharpZipLib? Does anyone know if I can do this without running through the entire zip by hand?

其他答案:

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

can extract one or more files based on a file filter (ie regular expressoin string)

Here’s the doc regarding the file filter:

// 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$"

so for a file named myfile.dat you could use “+.*myfile\.dat$” as your file filter.


VB.NET版, to extract specific files from Zip archivers. Comments in Spanish. Take a Zip file path, Filename you want extracted, password if needed. Extract to original path if OriginalPath is setted to 1, or use DestPath if OriginalPath=0. Keep an eye in “ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream” stuff…

It’s as follows:

''' <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

 

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明如何使用 SharpZipLib 解压某个具体文件?
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!