VB.NET 压缩解压字符串并以字符串格式返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24316954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET compress decompress string and return in string format
提问by Daniel Valland
I need a vb.net function for compressing/decompressing a string, and return the result as a string. I found these two functions:
我需要一个用于压缩/解压缩字符串的 vb.net 函数,并将结果作为字符串返回。我找到了这两个函数:
//Compress
Dim mem As New IO.MemoryStream
Dim gz As New System.IO.Compression.GZipStream(mem, IO.Compression.CompressionMode.Compress)
Dim sw As New IO.StreamWriter(gz)
sw.WriteLine("hello compression")
sw.Close()
//Decompress
Dim mem2 As New IO.MemoryStream(mem.ToArray)
gz = New System.IO.Compression.GZipStream(mem2, IO.Compression.CompressionMode.Decompress)
Dim sr As New IO.StreamReader(gz)
MsgBox(sr.ReadLine)
sr.Close()
But how do I make them return the compressed string as a string? thanks.
但是如何让他们将压缩字符串作为字符串返回?谢谢。
采纳答案by Andrew Cooper
You would need to Base64 encode the compressed byte array to get a string representation.
您需要对压缩的字节数组进行 Base64 编码以获得字符串表示形式。
Dim compressed As String = Convert.ToBase64String(mem.ToArray())
The decompressed string can just be read from the StreamReader.
解压后的字符串只能从StreamReader.
Dim decompressed As String = sr.ReadLine()

