我想压缩一个byte []并返回一个byte [](I want to compress a byte[] and return a byte[])

编程入门 行业动态 更新时间:2024-10-26 04:24:07
我想压缩一个byte []并返回一个byte [](I want to compress a byte[] and return a byte[])

我想在C#中编写一个方法,它接受一个byte []并将其压缩到另一个byte [],但我能找到的是从目录压缩到另一个目录( ZipFile库 )的库 。

是否可以仅使用.NET平台?

I want to write a method in C# that takes a byte[] and compress it to another byte[], but all I can find is libraries that compress from a directory to another directory (the ZipFile library).

Is it possible to do using only the .NET platform?

最满意答案

是否可以仅使用.NET平台?

当然 - 这正是System.IO.Compression命名空间的用途。 例如,您可以使用GZipStream类。 使用MemoryStream接收压缩数据,然后您可以调用ToArray 。

示例代码(未经测试):

public static byte[] Compress(byte[] data) { using (var output = new MemoryStream()) { using (var compression = new GZipStream(output, CompressionMode.Compress)) { compression.Write(data, 0, data.Length); } return output.ToArray(); } } public static byte[] Compress(byte[] data) { using (var output = new MemoryStream()) { using (var compression = new GZipStream(output, CompressionMode.Decompress)) {         compression.Write(data, 0, data.Length);     } return output.ToArray(); } }

您还可以使用DeflateStream作为替代压缩格式。

Is it possible to do using only the .NET platform?

Sure - that's exactly what the System.IO.Compression namespace is for. For example, you could use the GZipStream class. Use a MemoryStream to receive the compressed data, and then you can call ToArray afterwards.

Sample code (untested):

public static byte[] Compress(byte[] data) { using (var output = new MemoryStream()) { using (var compression = new GZipStream(output, CompressionMode.Compress)) { compression.Write(data, 0, data.Length); } return output.ToArray(); } } public static byte[] Compress(byte[] data) { using (var output = new MemoryStream()) { using (var compression = new GZipStream(output, CompressionMode.Decompress)) {         compression.Write(data, 0, data.Length);     } return output.ToArray(); } }

You could also use DeflateStream as an alternative compression form.

更多推荐

本文发布于:2023-07-26 02:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1269571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我想   byte   return   compress

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!