我想在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.
更多推荐
发布评论