我有一个VB.NET应用程序,它生成一个我需要发布到Web应用程序的XML文档。在发布XML之前,我需要压缩XML并对其进行base64编码。下面我有一个代码片段,我在其中使用XML字符串,使用gzip压缩然后使用base64编码。为了确保我正在做的是正确的,我然后解码base64,然后gzip解压缩。解压缩后,原始XML比我测试的XML长2个字节。我正在丢弃最后2个字节。他们去哪儿了?
Dim xml As String = ds.ToXMLString()
' compress and encode
Dim ceb() As Byte = System.Text.Encoding.UTF8.GetBytes(xml)
Dim cems As New System.IO.MemoryStream()
Dim cegz As New System.IO.Compression.GZipStream(cems, IO.Compression.CompressionMode.Compress)
cegz.Write(ceb, 0, ceb.Length)
Dim cees As String = System.Convert.ToBase64String(cems.ToArray())
' i want to make sure everything is working,
' decode and decompress and make sure it matches
Dim ddb() As Byte = System.Convert.FromBase64String(cees)
Dim ddms As New System.IO.MemoryStream(ddb)
Dim ddgz As New System.IO.Compression.GZipStream(ddms, IO.Compression.CompressionMode.Decompress)
Dim ddms2 As New System.IO.MemoryStream()
ddgz.CopyTo(ddms2)
Dim xmlRestored As String = System.Text.Encoding.UTF8.GetString(ddms2.ToArray())
Assert.AreEqual(xml.Substring(0, xmlRestored.Length), xmlRestored) ' <-- SUCCESS
Assert.AreEqual(xml.Length, xmlRestored.Length) ' <-- FAILS; xml.length=147802; xmlRestored.length=147800;
答案 0 :(得分:0)
没关系。我没有关闭我的压缩流。应该是这样的:
Dim xml As String = ds.ToXMLString()
' compress and encode
Dim ceb() As Byte = System.Text.Encoding.UTF8.GetBytes(xml)
Dim cems As New System.IO.MemoryStream()
Dim cegz As New System.IO.Compression.GZipStream(cems, IO.Compression.CompressionMode.Compress)
cegz.Write(ceb, 0, ceb.Length)
' i was missing the closing of the gzip stream
cegz.Close()
Dim cees As String = System.Convert.ToBase64String(cems.ToArray())
' i want to make sure everything is working,
' decode and decompress and make sure it matches
Dim ddb() As Byte = System.Convert.FromBase64String(cees)
Dim ddms As New System.IO.MemoryStream(ddb)
Dim ddgz As New System.IO.Compression.GZipStream(ddms, IO.Compression.CompressionMode.Decompress)
Dim ddms2 As New System.IO.MemoryStream()
ddgz.CopyTo(ddms2)
Dim xmlRestored As String = System.Text.Encoding.UTF8.GetString(ddms2.ToArray())
Assert.AreEqual(xml, xmlRestored) ' <-- SUCCESS
Assert.AreEqual(xml.Length, xmlRestored.Length) ' <-- SUCCESS