C#生成ZIP压缩包
生成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压缩包的更多相关文章
- PHP生成zip压缩包
/* * $res = new MakeZip($dir,$zipName); *@ $dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt' *@ $ ...
- 通过javascript在网页端生成zip压缩包并下载
zip.js是什么 zip.js的github项目地址:http://gildas-lormeau.github.io/zip.js/ 通过zip.js封装一个能在网页端生成zip文件的插件, 直接在 ...
- 【java工具类】生成Zip压缩包
多文件生成压缩包,返回压缩包生成位置的路径. FileUtil.java /** * 文件打压缩包 * @param files * @param Name * @return * @throws E ...
- python 生成zip压缩包
import zipfile file_name="a.txt" f = zipfile.ZipFile('test.zip','w',zipfile.ZIP_STORED) f. ...
- php生成zip压缩文件的方法,支持文件和压缩包路径查找
/* * new creatZip($_dir,$_zipName); *@ _dir是被压缩的文件夹名称,可使用路径,例 'a'或者'a/test.txt'或者'test.txt' *@ _zipN ...
- Node.js使用jszip实现打包zip压缩包
一.前言 最近有这样的一个需求,需要把两个同名的.mtl文件和.obj文件打包成一个同名的.zip压缩包.刚开始文件不多的时候,只有几个,或者十几个,甚至二三十个的时候,还能勉强接受手动修改,但是随着 ...
- java生成zip压缩文件,解压缩文件
1.生成zip public static void main(String[] args) { try { // testZip("c:\\temp.txt", "c: ...
- python 解压zip压缩包
在当前路径解压zip压缩包,生成同名文件夹,内部目录结构与压缩包一致 import zipfile import os def un_zip(file_name): """ ...
- MySQL8.0 zip压缩包版本 Windows下安装
MySQL zip压缩包版本 Windows下安装 Download MySQL Community Server 解压到相应的目录 我的解压目录:D:\Program Files\mysql-8.0 ...
随机推荐
- 走进JDK(二)------String
本文基于java8. 基本概念: Jvm 内存中 String 的表示是采用 unicode 编码 UTF-8 是 Unicode 的实现方式之一 一.String定义 public final cl ...
- CPU寻址
CPU组成和寄存器 1)CPU由运算器.控制器.寄存器等器件组成,这些器件靠内部总线相连 2)寄存器是CPU的组成部分,用来暂存指令.数据和地址,CPU对其读写速度是最快的,不需要IO传输 存储单元 ...
- sublime使用技巧汇总
sublime使用技巧 Ubuntu下安装sublime text 3143版本 Install the GPG key: wget -qO - https://download.sublimetex ...
- AI for VS ,美团创新之处分析
微软在2017中发布了VS Tools for AI,旨在提升用户对于深度学习的需求体验.AI组件可以让我们迅速构建和训练深度学习的Project,其功能主要有开发,调试和部署深度学习和人工智能的解决 ...
- Linux pwn入门教程(3)——ROP技术
作者:Tangerine@SAINTSEC 原文来自:https://bbs.ichunqiu.com/thread-42530-1-1.html 0×00 背景 在上一篇教程的<shellco ...
- Typescript 学习笔记五:类
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- IDEA 图标介绍。 缓存和索引介绍、清理方法和Debug使用
一.图标 二.缓存和索引 IntelliJ IDEA 的缓存和索引主要是用来加快文件查询,从而加快各种查找.代码提示等操作的速(上图中的图标能这样显示也是靠索引).某些特殊条件下,IntelliJ I ...
- LDO和DC-DC的概念,区别及优缺点
最近在做蓝牙项目的时候,遇到了需要配置这两种不同的供电模式的问题,这里顺便温习一下这种供电方式的概念,做个总结. LDO :LOW DROPOUT VOLTAGE 低压差线性稳压器,故名思意,为线性的 ...
- js中break、continue和return的一般用法总结
break break :终止break的整个循环体,包括内部所有循环.但对循环体外部的循环不影响. for(let i = 0;i<2;i++){ for(let j = 0;j<2;j ...
- JavaScript防篡改对象
不可扩展对象 默认情况下,所有对象都是可扩展的,使用Object.preventExtensions()方法可以改变这一行为. var person = { name: "Hiram&quo ...