使用DOTNETZIP过滤并压缩相对目录

业务要求:

  1. 压缩某个文件夹及其子目录
  2. 压缩时只压缩指定的文件类型,如cshtml
  3. 压缩后保持相对目录

 

找了很久,没有直接的DEMO,最后尝试通过以下代码完成

示例演示了只压缩cshtml和js,同时跳过debugjs和bin目录

 

 

  1. /// <summary>
  2.        ///
  3.        /// </summary>
  4.        /// <param name="args">
  5.        /// <example>
  6.        /// <code>
  7.        /// args = new string[] {
  8.        /// "ZipFile",
  9.        /// @"Path=D:\kljob\CardLan\CardLan.Web.OneCard",
  10.        /// "Filter=*.cshtml;*.js",
  11.        /// "TargetFile=d:\\temp\\zip.zip" ,
  12.        /// "ZipType=DotNet",
  13.        /// "SkipPath=DebugJS;bin"
  14.        /// };
  15.        ///
  16.        /// </code>
  17.        /// </example>
  18.        /// </param>
  19.        /// <returns></returns>
  20.        public static int Zip(string[] args)
  21.        {
  22.            string path = Helper.ArgHelper.FindArg(args, "Path");
  23.            string targetFile = Helper.ArgHelper.FindArg(args, "TargetFile");
  24.            string zipType = Helper.ArgHelper.FindArg(args, "ZipType");
  25.            string filter = Helper.ArgHelper.FindArg(args, "Filter");
  26.            string skipPath = Helper.ArgHelper.FindArg(args, "SkipPath");
  27.  
  28.  
  29.            if (!System.IO.Directory.Exists(path))
  30.                throw new System.IO.DirectoryNotFoundException(path);
  31.  
  32.  
  33.            switch (zipType)
  34.            {
  35.                case "DotNet":
  36.                default:
  37.                    using (ZipFile zip = new ZipFile(System.Text.Encoding.UTF8))//设置编码,解决压缩文件时中文乱码
  38.                    {
  39.                        StringBuilder sb = new StringBuilder("");
  40.                        foreach (var item in skipPath.Split(';'))
  41.                        {
  42.                            if (!string.IsNullOrEmpty(item))
  43.                                sb.AppendFormat("name!={1}\\{0}\\* and ", item,path);
  44.                        }
  45.                        zip.AddSelectedFiles(sb.ToString() + " (name=" + string.Join(" or name=", filter.Split(';')) + ")", path, "", true);
  46.                        zip.Save(targetFile);
  47.                    }
  48.                    return 0;
  49.            }
  50.        }

 

参考:

 

http://dotnetzip.herobo.com/DNZHelp/html/547e4c24-4683-96df-036e-19bc34ba27e4.htm

http://dotnetzip.herobo.com/DNZHelp/html/b5ca1211-94be-6039-cd07-61d3821d9c3d.htm

 

 

posted @ 2015-04-22 15:47  秦秋随  阅读(693)  评论(0编辑  收藏  举报