在Memorystream中压缩和解压缩
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Memorystream中压缩和解压缩相关的知识,希望对你有一定的参考价值。
我正在尝试在String中保存一些文件。
文件是压缩的,zip文件读取为ByteArray,ByteArray使用Convert.ToBase64String
转换为String。
当我以前创建一个实际的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中,我使用一个填充了原始byteArray的新Stream调用Unzip-Function,它失败,声称文件已损坏。
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
答案
我的道歉,如果有人试图深入研究这个 - 我自己找到了问题。它在这条线内:
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
以上是关于在Memorystream中压缩和解压缩的主要内容,如果未能解决你的问题,请参考以下文章