程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 如何壓縮多個文件/文件夾(GZipStream and C#)(1)

如何壓縮多個文件/文件夾(GZipStream and C#)(1)

編輯:關於C語言

在.Net Framework 2.0 中添加了System.IO.Compression 類來實現對文件的壓縮/解壓(GZipStream方 法),下面我們來看一個簡單的例子.

Code1:

1    public static void Compress(string filePath, string zipPath)
2    {
3      FileStream sourceFile = File.OpenRead(filePath);
4      FileStream destinationFile = File.Create(zipPath);
5      byte[] buffer = new byte[sourceFile.Length];
6      GZipStream zip = null;
7      try
8      {
9        sourceFile.Read(buffer, 0, buffer.Length);
10        zip = new GZipStream(destinationFile, CompressionMode.Compress);
11        zip.Write(buffer, 0, buffer.Length);
12      }
13      catch
14      {
15        throw;
16      }
17      finally
18      {
19        zip.Close();
20        sourceFile.Close();
21        destinationFile.Close();
22      }
23    }
24
25    public static void Decompress(string zipPath,string filePath)
26    {
27      FileStream sourceFile = File.OpenRead(zipPath);
28
29      string path = filePath.Replace(Path.GetFileName(filePath), "");
30
31      if(!Directory.Exists(path))
32        Directory.CreateDirectory(path);
33
34      FileStream destinationFile = File.Create(filePath);
35      GZipStream unzip = null;
36      byte[] buffer = new byte[sourceFile.Length];
37      try
38      {
39        unzip = new GZipStream(sourceFile, CompressionMode.Decompress, true);
40        int numberOfBytes = unzip.Read(buffer, 0, buffer.Length);
41
42        destinationFile.Write(buffer, 0, numberOfBytes);
43      }
44      catch
45      {
46        throw;
47      }
48      finally
49      {
50        sourceFile.Close();
51        destinationFile.Close();
52        unzip.Close();
53      }
54    }

用例:

1.壓縮

1      string folder = Path.Combine(Server.MapPath("~"), "TestCompress");
2      string file = "file1.txt";
3      string zip = "myzip";
4
5      SampleCompress.Compress(Path.Combine(folder, file), Path.Combine(folder, zip));

2.解壓

1      string folder = Path.Combine(Server.MapPath("~"), "TestCompress");
2      string file = "file1.txt";
3      string zip = "myzip";
4
5      SampleCompress.Decompress(Path.Combine(folder, zip),
Path.Combine (Path.Combine(folder, "zipfolder"), file));

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved