文件的压缩与解压
需引入 System.IO.Compression;
1.C#代码(入门案例)
Console.WriteLine("压缩文件...............");
using (FileStream fr = File.OpenRead("d:\\test.txt"))
{
using (FileStream fw = File.OpenWrite("d:\\test.zip"))
{
using (GZipStream gz = new GZipStream(fw, CompressionMode.Compress))
{ byte[] by = new byte[ * ];
int r = fr.Read(by, , by.Length);
while (r > )
{
gz.Write(by, , r);
r = fr.Read(by, , r);
}
}
}
}
Console.WriteLine("压缩完成。"); Console.WriteLine("解压文件...............");
using (FileStream fr = File.OpenRead("d:\\test.zip"))
{
using (GZipStream gz = new GZipStream(fr, CompressionMode.Decompress))
{
using (FileStream fw = File.OpenWrite("d:\\test2.txt"))
{ byte[] by = new byte[ * ];
int r = gz.Read(by, , by.Length);
while (r > )
{
fw.Write(by, , r);
r = gz.Read(by, , r);
}
}
}
}
Console.WriteLine("解压完成。"); Console.ReadKey();
2. 运行结果