在C#中,可以使用System.IO.Compression命名空间中的GZipStream类来实现gzip压缩和解压。下面是一个简单的示例代码:
using System;
using System.IO;
using System.IO.Compression;
public class GZipHelper
{
public static void CompressFile(string sourceFile, string compressedFile)
{
using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open))
{
using (FileStream compressedStream = File.Create(compressedFile))
{
using (GZipStream compressor = new GZipStream(compressedStream, CompressionMode.Compress))
{
sourceStream.CopyTo(compressor);
}
}
}
}
public static void DecompressFile(string compressedFile, string decompressedFile)
{
using (FileStream compressedStream = new FileStream(compressedFile, FileMode.Open))
{
using (FileStream decompressedStream = File.Create(decompressedFile))
{
using (GZipStream decompressor = new GZipStream(compressedStream, CompressionMode.Decompress))
{
decompressor.CopyTo(decompressedStream);
}
}
}
}
}
使用示例:
string sourceFile = "source.txt";
string compressedFile = "compressed.gz";
string decompressedFile = "decompressed.txt";
GZipHelper.CompressFile(sourceFile, compressedFile);
GZipHelper.DecompressFile(compressedFile, decompressedFile);
这样就可以实现对文件进行gzip压缩和解压缩操作。