有些项目为了更好的用户体验,会把下载文件做成一个压缩的文件,直接下载,免得去一个个的点击下载文件。网上有很多压缩文件的方法,也有第三方的分装DLL文件,本文主要介绍DotNetZip压缩方法。
DotNetZip的DLl下载地址:http://download.csdn.net/detail/lilinoscar/8295255
官网下载地址:http://dotnetzip.codeplex.com/
解决DotNetZip压缩中文名称乱码,只需要在实例化时设置编码:System.Text.Encoding.Default
即:ZipFile zip = new ZipFile(System.Text.Encoding.Default)。
解决DotNetZip压缩后的文件有多层目录:zip.AddFile(file,"");
AddFile加上第二个参数即可去掉多层的文件夹。
- #regionboolSaveFile(stringfilePath,byte[]bytes)文件保存,
- ///<summary>
- ///文件保存,特别是有些文件放到数据库,可以直接从数据取二进制,然后保存到指定文件夹
- ///</summary>
- ///<paramname="filePath">保存文件地址</param>
- ///<paramname="bytes">文件二进制</param>
- ///<returns></returns>
- publicstaticboolSaveFile(stringfilePath,byte[]bytes)
- {
- boolresult=true;
- try
- {
- using(varfileStream=newFileStream(filePath,FileMode.Create))
- {
- fileStream.Write(bytes,0,bytes.Length);
- }
- }
- catch(Exception)
- {
- result=false;
- }
- returnresult;
- }
- #endregion
- #region判断文件夹是否存在
- ///<summary>
- ///判断文件夹是否存在
- ///</summary>
- ///<paramname="path">文件夹地址</param>
- ///<returns></returns>
- publicstaticbooldirectoryExist(stringpath)
- {
- if(!string.IsNullOrEmpty(path)&&Directory.Exists(path))
- {
- returntrue;
- }
- returnfalse;
- }
- #endregion
- #region创建文件夹
- ///<summary>
- ///创建文件夹
- ///</summary>
- ///<paramname="path">文件地址</param>
- ///<returns></returns>
- publicstaticbooldirectoryAdd(stringpath)
- {
- if(!string.IsNullOrEmpty(path)&&!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);//新建文件夹
- returntrue;
- }
- returnfalse;
- }
- #endregion
- #region获取压缩后的文件路径
- ///<summary>
- ///获取压缩后的文件路径
- ///</summary>
- ///<paramname="dirPath">压缩的文件路径</param>
- ///<paramname="filesPath">多个文件路径</param>
- ///<returns></returns>
- publicstaticstringGetCompressPath(stringdirPath,List<string>filesPath)
- {
- varzipPath="";//返回压缩后的文件路径
- using(ZipFilezip=newZipFile(System.Text.Encoding.Default))//System.Text.Encoding.Default设置中文附件名称乱码,不设置会出现乱码
- {
- foreach(varfileinfilesPath)
- {
- zip.AddFile(file,"");
- //第二个参数为空,说明压缩的文件不会存在多层文件夹。比如C: estac.doc压缩后解压文件会出现c.doc
- //如果改成zip.AddFile(file);则会出现多层文件夹压缩,比如C: estac.doc压缩后解压文件会出现testac.doc
- }
- zipPath=string.Format("{0}\{1}.zip",dirPath,DateTime.Now.ToString("yyyyMMddHHmmss"));
- zip.Save(zipPath);
- }
- returnzipPath;
- }
- #endregion
调用:
- List<string>filesPath=newList<string>();
- filesPath.Add(“C:/test/a.doc”);
- filesPath.Add(“C:/test/b.doc”);
- //filesPath.Add(Server.MapPath("~/text/Files/c.doc"));//可以设置添加虚拟路径
- vardirPath="Server.MapPath("~/compress/")";
- varfilePath=GetCompressPath(dirPath,filesPath);//返回压缩的文件