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

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

以下是压缩的通用方法:

复制代码
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, "压缩后的文件名");

 

posted @   bky_xiaozhu  阅读(1277)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示