Asp.net中文件的压缩与解压

  这里笔者为大家介绍在asp.net中使用文件的压缩与解压。在asp.net中使用压缩给大家带来的好处是显而易见的,首先是减小了服务器端文件存储的空间,其次下载时候下载的是压缩文件想必也会有效果吧,特别是比较大的文件。有的客户可能会很粗心上传的是文件,那么可以通过判断后缀名来判断文件,不是压缩文件,就可以压缩文件,在存储。

  这里笔者引用了一个DLL文件(ICSharpCode.SharpZipLib.dll)(包含在本文代码中),调用其中的函数,就可以对文件进行压缩及解压了。其中压缩笔者主要用到的函数是

1 /// <summary>
2 /// 压缩文件
3 /// </summary>
4 /// <param name="fileName">要压缩的所有文件(完全路径)</param>
5 /// <param name="name">压缩后文件路径</param>
6 /// <param name="Level">压缩级别</param>
7   public void ZipFileMain(string[] filenames, string name, int Level)
8 {
9 ZipOutputStream s = new ZipOutputStream(File.Create(name));
10 Crc32 crc = new Crc32();
11 //压缩级别
12 s.SetLevel(Level); // 0 - store only to 9 - means best compression
13 try
14 {
15 foreach (string file in filenames)
16 {
17 //打开压缩文件
18 FileStream fs = File.OpenRead(file);
19
20 byte[] buffer = new byte[fs.Length];
21 fs.Read(buffer, 0, buffer.Length);
22
23 //建立压缩实体
24 ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(file));
25
26 //时间
27 entry.DateTime = DateTime.Now;
28
29 // set Size and the crc, because the information
30 // about the size and crc should be stored in the header
31 // if it is not set it is automatically written in the footer.
32 // (in this case size == crc == -1 in the header)
33 // Some ZIP programs have problems with zip files that don't store
34 // the size and crc in the header.
35 //空间大小
36 entry.Size = fs.Length;
37 fs.Close();
38 crc.Reset();
39 crc.Update(buffer);
40 entry.Crc = crc.Value;
41 s.PutNextEntry(entry);
42 s.Write(buffer, 0, buffer.Length);
43 }
44 }
45 catch
46 {
47 throw;
48 }
49 finally
50 {
51 s.Finish();
52 s.Close();
53 }
54
55 }

解压缩的主要代码

1 /// <summary>
2 /// 解压文件
3 /// </summary>
4 /// <param name="ZipPath">被解压的文件路径</param>
5 /// <param name="Path">解压后文件的路径</param>
6 public void UnZip(string ZipPath,string Path)
7 {
8 ZipInputStream s = new ZipInputStream(File.OpenRead(ZipPath));
9
10 ZipEntry theEntry;
11 try
12 {
13 while ((theEntry = s.GetNextEntry()) != null)
14 {
15 string fileName = System.IO.Path.GetFileName(theEntry.Name);
16
17 //生成解压目录
18 Directory.CreateDirectory(Path);
19
20 if (fileName != String.Empty)
21 {
22 //解压文件
23 FileStream streamWriter = File.Create(Path + fileName);
24
25 int size = 2048;
26 byte[] data = new byte[2048];
27 while (true)
28 {
29 size = s.Read(data, 0, data.Length);
30 if (size > 0)
31 {
32 streamWriter.Write(data, 0, size);
33 }
34 else
35 {
36
37 streamWriter.Close();
38 streamWriter.Dispose();
39 break;
40 }
41 }
42
43 streamWriter.Close();
44 streamWriter.Dispose();
45 }
46 }
47 }
48 catch
49 {
50 throw;
51 }
52 finally
53 {
54 s.Close();
55 s.Dispose();
56 }
57 }
58 }

那么我这里做了个简单的测试程序(点击下载

 

这里已知道要被压缩文件,这里只需填入要被压缩到的路径("D:\text\")解压路径一样。这里解压级别越大,压缩的就越厉害。

可以看测试小程序,将解压/压缩引入到你的项目中

好了,如果本文对你有作用请您留个言语,让笔者知道 ^_^

posted @ 2010-09-03 08:27  胡佳180815  阅读(10682)  评论(20编辑  收藏  举报