生成ZIP压缩包C#代码如下:

using System;
using System.Collections.Generic;
using System.Text; using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using log4net;
using log4net.Config; namespace Test.BLL
{
public class TestZipFile
{
protected static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); ///<summary>
/// 创建ZIP文件
///</summary>
public void CreateZipFile(string[] files, string sTempFile, string sPassWord)
{
try
{
using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
{
s.SetLevel(); // 压缩级别 0-9
if (sPassWord != "")
{
s.Password = sPassWord; //Zip压缩文件密码
} byte[] buffer = new byte[]; //缓冲区大小 foreach (string file in files)
{
if (!string.IsNullOrEmpty(file))
{
if (File.Exists(file))
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
else
{
logger.Error("文件:" + file + "不存在。");
}
}
} s.Finish();
s.Close();
}
}
catch (Exception ex)
{
logger.Error("压缩文件时异常!");
logger.Error("异常描述:\t" + ex.Message);
logger.Error("异常方法:\t" + ex.TargetSite);
logger.Error("异常堆栈:\t" + ex.StackTrace);
}
} /// <summary>
///
/// </summary>
/// <param name="files">放入ZIP的文件路劲(含文件名)</param>
/// <param name="sTempFile">创建的ZIP文件路劲(含文件名)</param>
/// <param name="sPassWord">ZIP文件密码</param>
/// <param name="folderNames">存放到ZIP中的文件夹名,空代表放在顶级目录</param>
public void CreateZipFileMutilFolder(string[] files, string sTempFile, string sPassWord, string[] folderNames)
{
try
{
using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
{
s.SetLevel(); // 压缩级别 0-9
if (sPassWord != "")
{
s.Password = sPassWord; //Zip压缩文件密码
} byte[] buffer = new byte[]; //缓冲区大小 int i = ;
foreach (string file in files)
{
if (!string.IsNullOrEmpty(file))
{
if (File.Exists(file))
{
ZipEntry entry = new ZipEntry((string.IsNullOrEmpty(folderNames[i]) ? "" : (folderNames[i] + "\\")) + Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
else
{
logger.Error("文件:" + file + "不存在。");
}
} i++;
} s.Finish();
s.Close();
}
}
catch (Exception ex)
{
logger.Error("压缩文件时异常!");
logger.Error("异常描述:\t" + ex.Message);
logger.Error("异常方法:\t" + ex.TargetSite);
logger.Error("异常堆栈:\t" + ex.StackTrace);
}
}
}
}

其中会用到的文件名、文件路径非法字符替换方法:

        /// <summary>
/// Remove invalid characters which are not allowed in the file name
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public string RemoveFileNameInvalidChar(string fileName)
{
if (string.IsNullOrEmpty(fileName)) return fileName; string invalidChars = new string(Path.GetInvalidFileNameChars()); string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars)); return Regex.Replace(fileName, invalidReStr, ""); } /// <summary>
/// Remove invalid characters which are not allowed in the path names
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string RemovePathInvalidChar(string filePath)
{ if (string.IsNullOrEmpty(filePath)) return filePath; string invalidChars = new string(Path.GetInvalidPathChars()); string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars)); return Regex.Replace(filePath, invalidReStr, ""); }

参考:http://jianyun.org/archives/959.html

ZIP DLL:http://files.cnblogs.com/xuezhizhang/ICSharpCode.SharpZipLib.zip

C#生成ZIP压缩包的更多相关文章

  1. PHP生成zip压缩包

    /* * $res = new MakeZip($dir,$zipName); *@ $dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt' *@ $ ...

  2. 通过javascript在网页端生成zip压缩包并下载

    zip.js是什么 zip.js的github项目地址:http://gildas-lormeau.github.io/zip.js/ 通过zip.js封装一个能在网页端生成zip文件的插件, 直接在 ...

  3. 【java工具类】生成Zip压缩包

    多文件生成压缩包,返回压缩包生成位置的路径. FileUtil.java /** * 文件打压缩包 * @param files * @param Name * @return * @throws E ...

  4. python 生成zip压缩包

    import zipfile file_name="a.txt" f = zipfile.ZipFile('test.zip','w',zipfile.ZIP_STORED) f. ...

  5. php生成zip压缩文件的方法,支持文件和压缩包路径查找

    /* * new creatZip($_dir,$_zipName); *@ _dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt' *@ _zipN ...

  6. Node.js使用jszip实现打包zip压缩包

    一.前言 最近有这样的一个需求,需要把两个同名的.mtl文件和.obj文件打包成一个同名的.zip压缩包.刚开始文件不多的时候,只有几个,或者十几个,甚至二三十个的时候,还能勉强接受手动修改,但是随着 ...

  7. java生成zip压缩文件,解压缩文件

    1.生成zip public static void main(String[] args) { try { // testZip("c:\\temp.txt", "c: ...

  8. python 解压zip压缩包

    在当前路径解压zip压缩包,生成同名文件夹,内部目录结构与压缩包一致 import zipfile import os def un_zip(file_name): """ ...

  9. MySQL8.0 zip压缩包版本 Windows下安装

    MySQL zip压缩包版本 Windows下安装 Download MySQL Community Server 解压到相应的目录 我的解压目录:D:\Program Files\mysql-8.0 ...

随机推荐

  1. 小程序页面传值e.currentTarget

    将页面确定上的数值5传到js 微信官网 wtml: <view class="distpicker-btn"> <view class="distpic ...

  2. 初识RabbitMQ

    1.安装 rabbitmq官网:http://www.rabbitmq.com/ 下载地址:https://packagecloud.io/rabbitmq 下载rabbitmq-server 安装脚 ...

  3. Java 线程使用注意事项

    事件处理线程说明 如果事件处理的逻辑能迅速完成,并且不会发起新的IO请求,比如只是在内存中记个标识,则直接在IO线程上处理更快,因为减少了线程池调度. 但如果事件处理逻辑较慢,或者需要发起新的IO请求 ...

  4. @WebFilter怎么控制多个filter的执行顺序

    转自:http://blog.csdn.net/liming_0820/article/details/53332070 之前我们控制多个filter的执行顺序是通过web.xml中控制filter的 ...

  5. MFC控件的颜色设置

    在绘制控件颜色时,控件会发送WM_CTLCOLOR消息给父窗口,父窗口收到消息后,映射到OnCtlColor()函数中处理. 该函数返回一个画刷用于设置子控件的背景颜色,子控件再执行自己的CtlCol ...

  6. 一些有价值的Blog推荐

    待看的一些文章 1. 性能调优攻略 http://coolshell.cn/articles/7490.html 2. 内存的存储管理--段式和页式管理的区别 http://blog.sina.com ...

  7. mysql数据库的常用知识

    问题一:如果使用可视化工具链接mysql? mysql默认情况下是不支持远程连接的!只需要几个步骤就能轻松搞定了. 1.vi /etc/mysql/my.cnf 修改里面bind-address项,将 ...

  8. Vue学习笔记八:v-for,v-if,v-show指令

    目录 v-for指令:遍历 HTML和效果图 v-for讲解 v-if和v-show:创建,删除,显示,隐藏 HTML和效果图 v-if和v-show的原理 v-for指令:遍历 HTML和效果图 有 ...

  9. CTFcrackTools-V3 - 一款旨在帮助 CTFer 在 CTF 中发挥作用的一个框架

    CTFcrackTools-V3 CTFcrackTools重置版 作者:米斯特安全-林晨.摇摆.奶权 米斯特安全团队首页:http://www.hi-ourlife.com/ 部分插件来源:希望团队 ...

  10. Android交流会-碎片Fragment,闲聊单位与尺寸

    女孩:又周末了哦~ 男孩:那么今日来开个交流会,我们也学一学人家高大尚的大会,自己开一个,广州站,Android开发攻城狮交流会~ 1.Fragment概要: Android从3.0开始引入了Frag ...