背景:要求压缩结果为XXX.zip/XXX文件名/XXX.xml

1、

 // <summary>
 /// 递归遍历目录
 /// </summary>
 /// <param name="strDirectory">The directory.</param>
 /// <param name="s">The ZipOutputStream Object.</param>
 /// <param name="parentPath">The parent path.</param>
 private void ZipSetp(string strDirectory, ICSharpCode.SharpZipLib.Zip.ZipOutputStream s, string parentPath)
 {
     if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
     {
         strDirectory += Path.DirectorySeparatorChar;
     }
     ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
     string[] filenames = Directory.GetFileSystemEntries(strDirectory);
     foreach (string file in filenames)// 遍历所有的文件和目录
     {
         if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
         {
             string pPath = parentPath;
             pPath += file.Substring(file.LastIndexOf("\\") + 1);
             pPath += "\\";
             ZipSetp(file, s, pPath);
         }
         else // 否则直接压缩文件
         {
             //打开压缩文件
             using (FileStream fs = File.OpenRead(file))
             {
                 byte[] buffer = new byte[fs.Length];
                 fs.Read(buffer, 0, buffer.Length);
                 string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + 1);
                 ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);

                 entry.DateTime = DateTime.Now;
                 entry.Size = fs.Length;
                 fs.Close();
                 crc.Reset();
                 crc.Update(buffer);
                 entry.Crc = crc.Value;
                 s.PutNextEntry(entry);
                 s.Write(buffer, 0, buffer.Length);
             }
         }
     }
 }

2、调用

//strDirectory为要压缩的文件地址

//zipedFile为压缩后的zip地址

public void ZipFileDirectory(string strDirectory, string zipedFile)
{
    Encoding gbk = Encoding.UTF8;
    ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage;

    using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))
    {
        using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ZipFile))
        {

          //包含文件目录进去
            string topDirName = Path.GetFileName(strDirectory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
            if (!string.IsNullOrEmpty(topDirName))
                topDirName += Path.DirectorySeparatorChar;
            ZipSetp(strDirectory, s, topDirName);
        }
    }
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐