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

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

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

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

         public static void CreateZip(List<string> directories, List<string> filenames, string zipFileName, string dir)
{
using (ZipOutputStream ZipStream = new ZipOutputStream(System.IO.File.Create(dir + zipFileName)))
{
ZipStream.SetLevel();
ZipEntryFactory factory = new ZipEntryFactory();
foreach (var directory in directories)
{
string virtualDirectory = directory;
ZipEntry zipEntry = factory.MakeDirectoryEntry(virtualDirectory);
zipEntry.DateTime = DateTime.Now;
ZipStream.PutNextEntry(zipEntry);
} byte[] buffer = new byte[];
for (int i = ; i < filenames.Count; i++)
{
string file = filenames[i];
string newfileName = file.Replace(dir, string.Empty);
ZipEntry entry = factory.MakeFileEntry(directories[i] + "//" + newfileName); entry.DateTime = DateTime.Now;
ZipStream.PutNextEntry(entry); using (FileStream fs = System.IO.File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
ZipStream.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
ZipStream.Finish();
ZipStream.Close();
} System.Web.HttpContext.Current.Response.ContentType = "application/x-compress zip";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + zipFileName);
System.Web.HttpContext.Current.Response.TransmitFile(dir + zipFileName);
}
以下载b目录为例,参数如下:
directories:

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

filenames:

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

zipFileName: 

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

dir:

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

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

上一篇:Spring MVC 教程,快速入门,深入分析(转载)


下一篇:Maven中更改默认JDK版本