C#使用ICSharpCode.SharpZipLib.dll压缩多个文件

首先通过NuGet管理安装ICSharpCode.SharpZipLib.dll

C#使用ICSharpCode.SharpZipLib.dll压缩多个文件_第1张图片

以下是压缩的通用方法:

using System;
using System.IO;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;

namespace Common
{
    /// <summary>
    /// 压缩文件帮助类
    /// </summary>
    public static class ZipHelper
    {
        /// <summary>
        /// 压缩多个文件
        /// </summary>
        /// <param name="filesToZip">要压缩的文件的相对路径集合</param>
        /// <param name="zipedFileName">压缩后的文件名</param>
     /// <param name="zipPassword">压缩密码</param>
/// <param name="blockSize">每次写入的缓冲区大小</param> /// <param name="zipLevel">压缩等级(0-9)</param> /// <returns></returns> public static string ZipFile(List<string> filesToZip, string zipedFileName, string zipPassword = "", int blockSize = 2048, int zipLevel = 9) { try { //压缩后的压缩文件相对路径 var newFileName = @"~/UploadFiles/Temp/" + zipedFileName + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".zip"; //压缩后的压缩文件物理地址 var zipedFilePath = HttpContext.Current.Server.MapPath(newFileName); //获取所有文件的物理地址 List<string> allFilesPath = new List<string>(); if (filesToZip != null && filesToZip.Any()) { filesToZip.ForEach(file => { var serverPath = HttpContext.Current.Server.MapPath(file); if (File.Exists(serverPath)) { allFilesPath.Add(serverPath); } }); } if (allFilesPath.Any()) { //创建临时目录 var directory = HttpContext.Current.Server.MapPath(@"~/UploadFiles/Temp"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } //创建压缩文件 ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFilePath)); zipStream.SetLevel(zipLevel); zipStream.Password = zipPassword; //写入所有文件到压缩文件 for (int i = 0; i < allFilesPath.Count; i++) { string strFilePath = allFilesPath[i];
              FileStream fs = null;
try { //被压缩的文件名 string strFileName = strFilePath.Substring(strFilePath.LastIndexOf("\\") + 1); ZipEntry entry = new ZipEntry(strFileName); entry.DateTime = DateTime.Now; zipStream.PutNextEntry(entry); //读取文件 fs = File.OpenRead(strFilePath); //缓冲区大小 byte[] buffer = new byte[blockSize]; int sizeRead = 0; do { sizeRead = fs.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sizeRead); } while (sizeRead > 0); } catch (Exception ex) { //continue; }
                        finally
                        {
                            if (fs != null)
                            {
                                fs.Close();
                                fs.Dispose();
                            }
                        } } zipStream.Finish(); zipStream.Close();
            //返回压缩后的压缩文件相对路径
return newFileName; } return string.Empty; } catch (Exception ex) { return string.Empty; } } } }

调用:

//要压缩的附件相对路径集合
List<string> filesToZip = new List<string>();
var
ziped_file = ZipHelper.ZipFile(filesToZip, "压缩后的文件名");

 

你可能感兴趣的:(C#使用ICSharpCode.SharpZipLib.dll压缩多个文件)