VB.NET 压缩 解压缩 字符串

发布于 2024-09-02 19:04:21 字数 72 浏览 5 评论 0原文

如何在 VB.NET 中压缩/解压缩字符串? 我正在尝试通过网络发送长字符串,并在发送之前需要它们尽可能小。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月静好 2024-09-09 19:04:21

您可以使用 GzipStream。

这是一个例子:

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

2年后编辑...

这对我来说不太有效,也许是因为我需要将数据存储在字节数组中。这适用于压缩:

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

然后对于解压缩,我只是将字节数组传递到 mem2 的构造函数而不是 mem.ToArray 中。

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.

走过海棠暮 2024-09-09 19:04:21

可以通过 GZipStream 传递它MemoryStream,然后检索压缩流并将其发送通过网络。压缩不是那么好,但它快速且易于编码。

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.

筱果果 2024-09-09 19:04:21

您还可以查看 Xceed 库。它比 GZipstream 速度更快,压缩效果也更好。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文