在C#中,可以使用以下幾種壓縮技術來壓縮和解壓縮數據:
using System;
using System.IO;
using System.IO.Compression;
public class GZipCompression
{
public static byte[] Compress(byte[] data)
{
using (MemoryStream output = new MemoryStream())
{
using (GZipStream compressor = new GZipStream(output, CompressionMode.Compress))
{
compressor.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
public static byte[] Decompress(byte[] data)
{
using (MemoryStream input = new MemoryStream(data))
{
using (MemoryStream output = new MemoryStream())
{
using (GZipStream decompressor = new GZipStream(input, CompressionMode.Decompress))
{
decompressor.CopyTo(output);
}
return output.ToArray();
}
}
}
}
using System;
using System.IO;
using System.IO.Compression;
public class DeflateCompression
{
public static byte[] Compress(byte[] data)
{
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream compressor = new DeflateStream(output, CompressionMode.Compress))
{
compressor.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
public static byte[] Decompress(byte[] data)
{
using (MemoryStream input = new MemoryStream(data))
{
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream decompressor = new DeflateStream(input, CompressionMode.Decompress))
{
decompressor.CopyTo(output);
}
return output.ToArray();
}
}
}
}
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip;
public class SharpZipLibCompression
{
public static byte[] Compress(byte[] data)
{
using (MemoryStream output = new MemoryStream())
{
using (GZipOutputStream compressor = new GZipOutputStream(output))
{
compressor.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
public static byte[] Decompress(byte[] data)
{
using (MemoryStream input = new MemoryStream(data))
{
using (MemoryStream output = new MemoryStream())
{
using (GZipInputStream decompressor = new GZipInputStream(input))
{
decompressor.CopyTo(output);
}
return output.ToArray();
}
}
}
}
以上是在C#中常用的幾種壓縮技術,開發人員可以根據具體需求選擇合適的壓縮算法來對數據進行壓縮和解壓縮。