如何从zip文件中获取单个文件?

时间:2015-02-06 10:40:30

标签: vb.net extract unzip

我想从VB.NET中的.zip文件中获取一个文件。我不需要提取所有.zip文件,只需要一个文件。

我正在使用框架4.5。

4 个答案:

答案 0 :(得分:2)

.NET Framework 4.5具有ZipFile类,可以为您执行此操作。这段代码可以帮助您入门:

Dim zipPath As String = "Sample.zip"
Using archive = ZipFile.Open(zipPath, ZipArchiveMode.Read)
  Dim entry = archive.GetEntry("MyFile.pdf")
  Using reader As New BinaryReader(entry.Open())
    System.IO.File.WriteAllBytes("MyFile.pdf", ReadAllBytes(reader))
  End Using
End Using

ReadAllBytes()是一个从二进制流中获取所有字节的辅助方法:

Public Shared Function ReadAllBytes(reader As BinaryReader) As Byte()
    Const bufferSize As Integer = 4096
    Using ms As New MemoryStream()
        Dim buffer(bufferSize) As Byte
        Dim count As Integer
        Do
            count = reader.Read(buffer, 0, buffer.Length)
            If count > 0 Then ms.Write(buffer, 0, count)
        Loop While count <> 0

        Return ms.ToArray()
    End Using
End Function

确保您使用的是.NET Framework 4.5或更高版本,并且已包含对System.IO.CompressionSystem.IO.Compression.FileSystem的引用。

答案 1 :(得分:0)

DotNetZip

的帮助下尝试使用此代码
Using zip As ZipFile = ZipFile.Read(ExistingZipFile)
    Dim e As ZipEntry = zip("DocumentToFind.txt")
    e.Extract(OutputStream)
End Using

否则你可以这样使用ZipArchiveClass

Using zip As ZipArchive = ZipFile.Open(zipfile, ZipArchiveMode.Read)
Dim file = zip.Entries.Where(Function(x) x.Name = "fileToFind")
If file IsNot Nothing Then
    file.ExtractToFile("yourFile")

End If

结束使用

答案 2 :(得分:0)

这将允许您逐行读取文本中的txt文件

Dim zipPath As String = "ZIP FILE LOCATION"
        Using zipStream = New FileStream(last_pafx23_open, FileMode.Open)
            Using archive = New ZipArchive(zipStream, ZipArchiveMode.Read)
                For Each ent In archive.Entries
                    MsgBox(ent.ToString)
                    Using stream = ent.Open()
                        Using reader = New StreamReader(stream)
                            While Not reader.EndOfStream
                                MsgBox(reader.ReadLine)
                            End While
                        End Using
                    End Using
                Next
            End Using
        End Using

答案 3 :(得分:-1)

使用ReadAllBytes()辅助函数跳过BinaryReader,改为使用ExtractToFile():

Imports System.IO.Compression

Using archive = ZipFile.Open("Sample.zip", ZipArchiveMode.Read)
  Dim entry = archive.GetEntry("MyFile.pdf")
  If entry IsNot Nothing then entry.ExtractToFile("MyFile.pdf")
End Using

当然还需要System.IO.CompressionSystem.IO.Compression.FileSystem的引用。