阅读量:0
C#中可以使用System.IO.Compression命名空间来实现缓冲区的数据压缩和解压缩。以下是一个简单的示例代码:
using System; using System.IO; using System.IO.Compression; public class CompressionExample { public static byte[] CompressData(byte[] data) { using (MemoryStream compressedStream = new MemoryStream()) { using (DeflateStream compressionStream = new DeflateStream(compressedStream, CompressionMode.Compress)) { compressionStream.Write(data, 0, data.Length); } return compressedStream.ToArray(); } } public static byte[] DecompressData(byte[] data) { using (MemoryStream compressedStream = new MemoryStream(data)) { using (MemoryStream decompressedStream = new MemoryStream()) { using (DeflateStream decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress)) { decompressionStream.CopyTo(decompressedStream); } return decompressedStream.ToArray(); } } } public static void Main(string[] args) { byte[] originalData = new byte[] { 1, 2, 3, 4, 5 }; byte[] compressedData = CompressData(originalData); byte[] decompressedData = DecompressData(compressedData); Console.WriteLine("Original Data: " + BitConverter.ToString(originalData)); Console.WriteLine("Compressed Data: " + BitConverter.ToString(compressedData)); Console.WriteLine("Decompressed Data: " + BitConverter.ToString(decompressedData)); } }
在这个示例中,我们首先定义了一个CompressData方法来压缩数据,接着定义了一个DecompressData方法来解压缩数据。最后,在Main方法中,我们可以看到如何使用这两个方法来对数据进行压缩和解压缩操作。