使用 ICharpCode.SharpZipLib 压缩指定目录结构

今天做项目中遇见一个压缩问题,我的目录结构是树形菜单,文件在服务器存储是平面存储,没有目录结构,所以在下载指定目录的时候要构建目录结构,如下:

当我右键点击下载b目录文件夹的时候要Download  b 目录下的所有文件,并且有目录结构,实现如下:

 1         public static void CreateZip(List<string> directories, List<string> filenames, string zipFileName, string dir)
 2         {
 3             using (ZipOutputStream ZipStream = new ZipOutputStream(System.IO.File.Create(dir + zipFileName)))
 4             {
 5                 ZipStream.SetLevel(9);
 6                 ZipEntryFactory factory = new ZipEntryFactory();
 7                 foreach (var directory in directories)
 8                 {
 9                     string virtualDirectory = directory;
10                     ZipEntry zipEntry = factory.MakeDirectoryEntry(virtualDirectory);
11                     zipEntry.DateTime = DateTime.Now;
12                     ZipStream.PutNextEntry(zipEntry);
13                 }
14 
15                 byte[] buffer = new byte[4096];
16                 for (int i = 0; i < filenames.Count; i++)
17                 {
18                     string file = filenames[i];
19                     string newfileName = file.Replace(dir, string.Empty);
20                     ZipEntry entry = factory.MakeFileEntry(directories[i] + "//" + newfileName);
21 
22                     entry.DateTime = DateTime.Now;
23                     ZipStream.PutNextEntry(entry);
24 
25                     using (FileStream fs = System.IO.File.OpenRead(file))
26                     {
27                         int sourceBytes;
28                         do
29                         {
30                             sourceBytes = fs.Read(buffer, 0, buffer.Length);
31                             ZipStream.Write(buffer, 0, sourceBytes);
32                         } while (sourceBytes > 0);
33                     }
34                 }
35                 ZipStream.Finish();
36                 ZipStream.Close();
37             }
38 
39             System.Web.HttpContext.Current.Response.ContentType = "application/x-compress zip";
40             System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + zipFileName);
41             System.Web.HttpContext.Current.Response.TransmitFile(dir + zipFileName);
42         }
以下载b目录为例,参数如下:
directories:

filenames:

zipFileName: 

 dir:

调用上面方法传入正确参数即可生成正确的目录


posted @ 2013-12-11 10:02  一米,希望  阅读(1196)  评论(0编辑  收藏  举报