在.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");
Path.Combine (Path.Combine(folder, "zipfolder"), file));
2 string file = "file1.txt";
3 string zip = "myzip";
4
5 SampleCompress.Decompress(Path.Combine(folder, zip),