VB.NET compress Decompress String

2019-02-19 13:16发布

问题:

How do I compress/decompress a string in VB.NET ? I am trying to send long string through the Network and need them to be as small as possible before sending.

Thanks

回答1:

You could use GzipStream.

Here is an example:

//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()

edit 2 years later...

That didn't quite work for me, perhaps because I needed to store the data in a byte array. This worked for Compress:

'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.Write(value)
 mem.Seek(0, IO.SeekOrigin.Begin)
 Dim sr As New IO.BinaryReader(mem)
 _zippedXML = sr.ReadBytes(CInt(mem.Length))
 sw.Close()

Then for Decompress I just passed the byte array into the constructor of mem2 instead of mem.ToArray.



回答2:

Could pass it through a GZipStream over a MemoryStream, then retrieve the compressed stream to send it over the network. Not that great compression, but it's fast and easy to code.



回答3:

You can also take a look at Xceed library. Its faster and the it also compresses a lot better than GZipstream.