C#实现文件的压缩与解压 C#使用GZipStream实现文件的压缩与解压
在代码的世界里游走 人气:0需引入 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[1024 * 1024]; int r = fr.Read(by, 0, by.Length); while (r > 0) { gz.Write(by, 0, r); r = fr.Read(by, 0, 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[1024 * 1024]; int r = gz.Read(by, 0, by.Length); while (r > 0) { fw.Write(by, 0, r); r = gz.Read(by, 0, r); } } } } Console.WriteLine("解压完成。"); Console.ReadKey();
2. 运行结果
加载全部内容