C# -- 文件的压缩与解压(GZipStream)
文件的压缩与解压
需引入 System.IO.Compression;
1.C#代码(入门案例)
1 Console.WriteLine("压缩文件..............."); 2 using (FileStream fr = File.OpenRead("d:\test.txt")) 3 { 4 using (FileStream fw = File.OpenWrite("d:\test.zip")) 5 { 6 using (GZipStream gz = new GZipStream(fw, CompressionMode.Compress)) 7 { 8 9 byte[] by = new byte[1024 * 1024]; 10 int r = fr.Read(by, 0, by.Length); 11 while (r > 0) 12 { 13 gz.Write(by, 0, r); 14 r = fr.Read(by, 0, r); 15 } 16 } 17 } 18 } 19 Console.WriteLine("压缩完成。"); 20 21 22 Console.WriteLine("解压文件..............."); 23 using (FileStream fr = File.OpenRead("d:\test.zip")) 24 { 25 using (GZipStream gz = new GZipStream(fr, CompressionMode.Decompress)) 26 { 27 using (FileStream fw = File.OpenWrite("d:\test2.txt")) 28 { 29 30 byte[] by = new byte[1024 * 1024]; 31 int r = gz.Read(by, 0, by.Length); 32 while (r > 0) 33 { 34 fw.Write(by, 0, r); 35 r = gz.Read(by, 0, r); 36 } 37 } 38 } 39 } 40 Console.WriteLine("解压完成。"); 41 42 Console.ReadKey();
2. 运行结果