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

How to get single file from zip file?

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

我正在使用框架 4.5。

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

结束使用

.NET Framework 4.5 具有 ZipFile class 可以为您完成此操作。这段代码应该可以帮助您入门:

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.

的引用

这将允许您逐行读取 zip 文件中的 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

跳过带 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