在Memorystream中压缩和解压缩

时间:2018-09-12 14:43:43

标签: .net vb.net stream

我正在尝试将某些文件保存在字符串中。

压缩文件,将zipfile读取为ByteArray,然后使用Convert.ToBase64String将ByteArray转换为字符串。

当我用来创建实际的Zip文件时,它可以工作,但是现在我试图在MemoryStream中进行操作,我得到了:

  

FileFormatException:“文件包含损坏的数据。”

这是我用来诊断问题的功能:

Private Sub PushToBase64StringStream(tSourceDirPath As String)
    Dim byteArray() As Byte

    Using cStream As New MemoryStream
        ZipManagedFilesStream(cStream, tSourceDirPath)

        cStream.Seek(0, SeekOrigin.Begin)
        byteArray = New Byte(CType(cStream.Length, Integer)) {}
        cStream.Read(byteArray, 0, CInt(cStream.Length))
        'Base64String = Convert.ToBase64String(byteArray)

        ' This statement works
        Using cPackage As Package = Package.Open(cStream, FileMode.Open, FileAccess.Read)
    End Using

    Using cStream2 As New MemoryStream
        cStream2.Write(byteArray, 0, byteArray.Length)
        cStream2.Seek(0, SeekOrigin.Begin)

        ' This statement fails
        Using cPackage As Package = Package.Open(cStream2, FileMode.Open, FileAccess.Read)
        End Using
    End Using

End Sub

在第一个Using-Statement中,我使用原始流调用Unzip-Function,它可以工作。在第二个Using-Statement中,我使用新的Stream调用Unzip-Function,该Stream用原始的byteArray填充,并且失败,声称文件已损坏。

Private Sub ZipManagedFilesStream(cStream As Stream, tSourceDirectory As String)
    Using cPackage As Package = Package.Open(cStream, FileMode.Create)
        For Each cFile As FileInfo In ManagedFiles(tSourceDirectory)

            Dim tType As String = Net.Mime.MediaTypeNames.Application.Zip
            Dim cPartUri As New Uri("/" & cFile.Name, UriKind.Relative)
            Dim cPackagePart As PackagePart = cPackage.CreatePart(cPartUri, tType, CompressionOption.Normal)

            Using cSourceStream As New FileStream(cFile.FullName, FileMode.Open, FileAccess.Read),
                  cTargetStream As Stream = cPackagePart.GetStream
                cSourceStream.CopyTo(cTargetStream)
            End Using
        Next
    End Using
End Sub

1 个答案:

答案 0 :(得分:0)

我的道歉,如果有人试图对此进行深入探讨-我自己发现了问题。它位于此行内:

byteArray = New Byte(CType(cStream.Length, Integer)) {}

ByteArray太长了1个字节。我将其更改为:

byteArray = New Byte(CType(cStream.Length - 1, Integer)) {}

现在可以了。


编辑:这样做更容易:

Using cStream As New MemoryStream
    ZipManagedFilesStream(cStream, tSourceDirPath)
    Base64String = Convert.ToBase64String(cStream.ToArray)
End Using