C#使用GZipStream实现文件的压缩与解压

时间:2022-09-12 12:54:40

本文实例为大家分享了c#实现文件的压缩与解压的具体代码,供大家参考,具体内容如下

需引入 system.io.compression;

1.c#代码(入门案例)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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. 运行结果

C#使用GZipStream实现文件的压缩与解压

C#使用GZipStream实现文件的压缩与解压

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/ChengWenHao/p/YaSuoAndJieYa.html