如何压缩多个文件/文件夹(GZipStream and C#)(上)

在.Net Framework 2.0 中添加了System.IO.Compression 类来实现对文件的压缩/解压(GZipStream方法),下面我们来看一个简单的例子.

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    }

 

posted @ 2013-08-13 22:28  Net-Spider  阅读(497)  评论(0)    收藏  举报