生成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. s5-6 Linux 标准输出 系统优化 目录结构

    标准输出 重定向符号 #>   1>    标准输出重定向  先把文件的内容清空   把内容放在文件的最后一行 #>>  1>>   追加重定向      把内容放 ...

  2. 第34 memcached缓存

    1.缓存数据库 缓存:将数据存储在内存中,只有当磁盘胜任不了的时候,才会启用缓存. 缺点:断电数据丢失(双电),用缓存存储数据的目的只是为了应付大并发的业务,至于数据存储及可靠性不要找他了.   数据 ...

  3. Shell脚本学习-数组

    跟着RUNOOB网站的教程学习的笔记 Shell数组 数组中可以存放多个值,Bash Shell只支持一维数组(不支持多维数组),初始化时不需要定义数组大小(与PHP类似). 与大部分编程语言类似,数 ...

  4. wx:for类表渲染

    列表渲染 wx:for 在组件上使用wx:for控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件. 默认数组的当前项的下标变量名默认为index,数组当前项的变量名默认为item < ...

  5. Beta冲刺 (4/7)

    Part.1 开篇 队名:彳艮彳亍团队 组长博客:戳我进入 作业博客:班级博客本次作业的链接 Part.2 成员汇报 组员1(组长)柯奇豪 过去两天完成了哪些任务 共享编辑文章的后端数据处理 展示Gi ...

  6. 如何将uniurlframe中html调用delphi的函数

    uniGUI总群中台中cmj朋友为我们总结了如下内容,对于利用delphi+uniGUI开发应用,可以说是精品,必须掌握. 一句话,如何在html与delphi间交互代码,是最好的答案. [Clien ...

  7. Linux合上笔记本不进入休眠模式

      最近一个问题困扰了我很久,入职之前和人事说过工作中会用自己的电脑,但是人事还是坚持要给我发一个电脑,没办法,公司没有补贴,那就领了吧,索性将这个笔记本配置成了Fedora系统,用来当测试机,但是一 ...

  8. SDWebImage之SDWebImageCompat

    SDWebImageCompat 是SDWebImage 的配置文件,里面利用条件编译对Apple 的各个平台进行了兼容.从源码中可以看到SDWebImage 支持当前的MAC/iOS/TV/WATC ...

  9. 在虚拟机上安装redis集群,redis使用版本为4.0.5,本机通过命令客户端可以连接访问,外部主机一直访问不了

    在虚拟机上安装了redis 4 ,启动后本机客户端可以连接访问,但是外部主机一直访问不了,在使用java代码连接redis集群时报:no reachable node in cluster,原因:在r ...

  10. ElasticSearch权威指南学习(映射和分析)

    概念 映射(mapping)机制用于进行字段类型确认,将每个字段匹配为一种确定的数据类型(string, number, booleans, date等).+ 分析(analysis)机制用于进行全文 ...