在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壓縮和解壓縮操作。