在C#中,可以使用System.IO.Compression命名空间中的GZipStream类来实现文件的压缩与解压缩。
以下是一个示例代码,展示了如何使用GZipStream类进行压缩和解压:
internal class Program
{
static void Main(string[] args)
{
string source = @"C:\Users\86155\Desktop\4.zip";
string target = @"C:\Users\86155\Desktop\5.txt";
JieYa(source, target);
Console.WriteLine("OK");
Console.ReadKey();
}
static void YaSuo(string source, string target)
{
using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
{
using (FileStream fsWrite = new FileStream(target, FileMode.Create, FileAccess.Write))
{
using (GZipStream gs = new GZipStream(fsWrite, CompressionMode.Compress))
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = 0;
while ((r = fsRead.Read(buffer, 0, buffer.Length)) > 0)
{
gs.Write(buffer, 0, r);
}
}
}
}
}
static void JieYa(string source, string target)
{
using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
{
using (FileStream fsWrite = new FileStream(target, FileMode.Create, FileAccess.Write))
{
using (GZipStream gs = new GZipStream(fsRead,CompressionMode.Decompress))
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = 0;
while ((r = gs.Read(buffer, 0, buffer.Length)) > 0)
{
fsWrite.Write(buffer, 0, r);
}
}
}
}
}
}
在上面的示例代码中,CompressFile
方法接受一个源文件路径和一个压缩文件路径作为参数。它使用FileStream
打开源文件,并使用File.Create
创建压缩文件。然后,它使用GZipStream
来创建压缩流,并将源文件复制到压缩流中。最后,压缩流将压缩的数据写入压缩文件。
类似地,DecompressFile
方法接受一个压缩文件路径和一个解压缩文件路径作为参数。它使用FileStream
打开压缩文件,并使用File.Create
创建解压缩文件。然后,它使用GZipStream
来创建解压缩流,并将压缩文件复制到解压缩流中。最后,解压缩流将解压缩的数据写入解压缩文件。
上述代码仅仅实现了基本的文件压缩和解压功能。如果需要处理更多压缩和解压选项,如密码保护、处理文件夹等,可以参考GZipStream类和其他相关类的更多用法和选项。