使用ICSharpCode.SharpZipLib.Zip实现压缩与解压缩
使用开源类库ICSharpCode.SharpZipLib.Zip可以实现压缩与解压缩功能,源代码和DLL可以从http://www.icsharpcode.net/OpenSource/SharpZipLib/Default.aspx下载;
有两种方式可以实现压缩与解压缩,这里只提供了ZIP格式;
1、DLL本身提供的快速压缩与解压缩,直接代码:
using System;
using ICSharpCode.SharpZipLib.Zip; namespace Zip
{
public static class FastZipHelper
{
#region CreateZipFile public static bool CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter,
string directoryFilter, bool createEmptyDirectories,
bool restoreAttributesOnExtract, bool restoreDateTimeOnExtract)
{
try
{
FastZip fastZip = new FastZip();
fastZip.CreateEmptyDirectories = createEmptyDirectories;
fastZip.RestoreAttributesOnExtract = restoreAttributesOnExtract;
fastZip.RestoreDateTimeOnExtract = restoreDateTimeOnExtract;
fastZip.CreateZip(zipFileName, sourceDirectory, recurse, fileFilter, directoryFilter);
return true;
}
catch (Exception ex)
{
return false;
}
} public static bool CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter,
string directoryFilter, bool createEmptyDirectories)
{
return CreateZip(zipFileName, sourceDirectory, recurse, fileFilter, directoryFilter, createEmptyDirectories,
true, true);
} public static bool CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter,
string directoryFilter)
{
return CreateZip(zipFileName, sourceDirectory, recurse, fileFilter, directoryFilter, true);
} public static bool CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter)
{
return CreateZip(zipFileName, sourceDirectory, recurse, fileFilter, string.Empty);
} public static bool CreateZip(string zipFileName, string sourceDirectory, bool recurse)
{
return CreateZip(zipFileName, sourceDirectory, recurse, string.Empty);
} public static bool CreateZip(string zipFileName, string sourceDirectory)
{
return CreateZip(zipFileName, sourceDirectory, true);
} #endregion #region ExtractZip public static bool ExtractZip(string zipFileName, string targetDirectory, FastZip.Overwrite overwrite,
FastZip.ConfirmOverwriteDelegate confirmDelegate, string fileFilter,
string directoryFilter, bool restoreDateTime, bool createEmptyDirectories,
bool restoreAttributesOnExtract, bool restoreDateTimeOnExtract)
{
try
{
FastZip fastZip = new FastZip();
fastZip.CreateEmptyDirectories = createEmptyDirectories;
fastZip.RestoreAttributesOnExtract = restoreAttributesOnExtract;
fastZip.RestoreDateTimeOnExtract = restoreDateTimeOnExtract;
fastZip.ExtractZip(zipFileName, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter,
restoreDateTime);
return true;
}
catch (Exception ex)
{
return false;
}
} public static bool ExtractZip(string zipFileName, string targetDirectory, FastZip.Overwrite overwrite,
FastZip.ConfirmOverwriteDelegate confirmDelegate, string fileFilter,
string directoryFilter, bool restoreDateTime, bool createEmptyDirectories)
{
return ExtractZip(zipFileName, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter,
restoreDateTime, createEmptyDirectories, true, true);
} public static bool ExtractZip(string zipFileName, string targetDirectory, FastZip.Overwrite overwrite,
FastZip.ConfirmOverwriteDelegate confirmDelegate, string fileFilter,
string directoryFilter, bool restoreDateTime)
{
return ExtractZip(zipFileName, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter,
restoreDateTime, true);
} public static bool ExtractZip(string zipFileName, string targetDirectory, FastZip.Overwrite overwrite,
FastZip.ConfirmOverwriteDelegate confirmDelegate, string fileFilter,
string directoryFilter)
{
return ExtractZip(zipFileName, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter,
true);
} public static bool ExtractZip(string zipFileName, string targetDirectory, FastZip.Overwrite overwrite,
FastZip.ConfirmOverwriteDelegate confirmDelegate, string fileFilter)
{
return ExtractZip(zipFileName, targetDirectory, overwrite, confirmDelegate, fileFilter, string.Empty);
} public static bool ExtractZip(string zipFileName, string targetDirectory)
{
return ExtractZip(zipFileName, targetDirectory, string.Empty);
} public static bool ExtractZip(string zipFileName, string targetDirectory, string fileFilter)
{
return ExtractZip(zipFileName, targetDirectory, FastZip.Overwrite.Always, null, fileFilter);
} #endregion
}
}
2、自己实现:
using System;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip; namespace Zip
{
public static class ZipHelper
{
public static string[] GetDirectories(string sourceDirectory)
{
List<string> result = new List<string>(); string[] directories = Directory.GetDirectories(sourceDirectory);
if (directories.Length > 0)
{
foreach (var directory in directories)
{
result.Add(directory);
result.AddRange(GetDirectories(directory));
}
}
return result.ToArray();
} public static string[] GetFiles(string sourceDirectory)
{
List<string> result = new List<string>();
result.AddRange(Directory.GetFiles(sourceDirectory));
string[] directories = Directory.GetDirectories(sourceDirectory);
if (directories.Length > 0)
{
foreach (var directory in directories)
{
result.AddRange(GetFiles(directory));
}
}
return result.ToArray();
} #region CreateZipFile public static void CreateZip(string sourceDirectory)
{
CreateZip(sourceDirectory, null);
} public static void CreateZip(string sourceDirectory, string zipFileName)
{
if (string.IsNullOrEmpty(sourceDirectory))
{
throw new ArgumentNullException("sourceDirectory", "sourceDirectory can not be null or empty.");
}
if (!Directory.Exists(sourceDirectory))
{
throw new DirectoryNotFoundException(sourceDirectory + " can not be found.");
}
if (string.IsNullOrEmpty(zipFileName))
{
zipFileName = sourceDirectory.TrimEnd('\\').TrimEnd('/') + ".zip";
}
// Depending on the directory this could be very large and would require more attention
// in a commercial package.
//string[] filenames = Directory.GetFiles(sourceDirectory);
string[] directories = GetDirectories(sourceDirectory);
string[] filenames = GetFiles(sourceDirectory);
if (!Directory.Exists(Path.GetDirectoryName(zipFileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(zipFileName));
}
// 'using' statements guarantee the stream is closed properly which is a big source
// of problems otherwise. Its exception safe as well which is great.
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
{
s.SetLevel(9); // 0 - store only to 9 - means best compression ZipEntryFactory factory = new ZipEntryFactory();
foreach (var directory in directories)
{
string virtualDirectory = directory.Replace(sourceDirectory, string.Empty);
ZipEntry zipEntry = factory.MakeDirectoryEntry(virtualDirectory);
zipEntry.DateTime = DateTime.Now;
s.PutNextEntry(zipEntry);
} byte[] buffer = new byte[4096]; foreach (string file in filenames)
{
// Using GetFileName makes the result compatible with XP
// as the resulting path is not absolute.
string newfileName = file.Replace(sourceDirectory, string.Empty);
ZipEntry entry = factory.MakeFileEntry(newfileName); // Setup the entry data as required. // Crc and size are handled by the library for seakable streams
// so no need to do them here. // Could also use the last write time or similar for the file.
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file))
{
// Using a fixed size buffer here makes no noticeable difference for output
// but keeps a lid on memory usage.
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
} // Finish/Close arent needed strictly as the using statement does this automatically // Finish is important to ensure trailing information for a Zip file is appended. Without this
// the created file would be invalid.
s.Finish(); // Close is important to wrap things up and unlock the file.
s.Close();
}
} #endregion #region ExtractZip public static void ExtractZip(string zipFileName)
{
ExtractZip(zipFileName, null);
} public static void ExtractZip(string zipFileName, string targetDirectory)
{
if (string.IsNullOrEmpty(zipFileName))
{
throw new ArgumentNullException("zipFileName", "zipFileName can not be null or empty.");
} if (!File.Exists(zipFileName))
{
throw new FileNotFoundException(zipFileName + " can not be found.");
} if (string.IsNullOrEmpty(targetDirectory))
{
targetDirectory = Path.Combine(Path.GetDirectoryName(zipFileName),
Path.GetFileNameWithoutExtension(zipFileName));
}
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
//create directory
string targetPath = Path.Combine(targetDirectory, theEntry.Name);
if (theEntry.IsDirectory)
{
Directory.CreateDirectory(targetPath);
}
if (theEntry.IsFile)
{
if (!Directory.Exists(Path.GetDirectoryName(targetPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
}
using (FileStream streamWriter = File.Create(targetPath))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
} #endregion
}
}
使用ICSharpCode.SharpZipLib.Zip实现压缩与解压缩的更多相关文章
- 基于ICSharpCode.SharpZipLib.Zip的压缩解压缩
原文:基于ICSharpCode.SharpZipLib.Zip的压缩解压缩 今天记压缩解压缩的使用,是基于开源项目ICSharpCode.SharpZipLib.Zip的使用. 一.压缩: /// ...
- C#调用 ICSharpCode.SharpZipLib.Zip 实现解压缩功能公用类
最近想用个解压缩功能 从网上找了找 加自己修改,个人感觉还是比较好用的,直接上代码如下 using System; using System.Linq; using System.IO; using ...
- 利用ICSharpCode.SharpZipLib.Zip进行文件压缩
官网http://www.icsharpcode.net/ 支持文件和字符压缩. 创建全新的压缩包 第一步,创建压缩包 using ICSharpCode.SharpZipLib.Zip; ZipOu ...
- C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...
- C# ZipHelper C#公共类 -- ICSharpCode.SharpZipLib.dll实现压缩和解压
关于本文档的说明 本文档基于ICSharpCode.SharpZipLib.dll的封装,常用的解压和压缩方法都已经涵盖在内,都是经过项目实战积累下来的 1.基本介绍 由于项目中需要用到各种压缩将文件 ...
- 使用NPOI读取Excel报错ICSharpCode.SharpZipLib.Zip.ZipException:Wrong Local header signature
写了一个小程序利用NPOI来读取Excel,弹出这样的报错: ICSharpCode.SharpZipLib.Zip.ZipException:Wrong Local header signature ...
- C# 利用ICSharpCode.SharpZipLib.dll 实现压缩和解压缩文件
我们 开发时经常会遇到需要压缩文件的需求,利用C#的开源组件ICSharpCode.SharpZipLib, 就可以很容易的实现压缩和解压缩功能. 压缩文件: /// <summary> ...
- ICSharpCode.SharpZipLib.Zip
//压缩整个目录下载 var projectFolder = Request.Params["folder"] != null ? Request.Params["fol ...
- 利用Java进行zip文件压缩与解压缩
摘自: https://www.cnblogs.com/alphajuns/p/12442315.html 工具类: package com.alphajuns.util; import java.i ...
随机推荐
- [转] 三步将你的 React Native 项目运行在 Web 浏览器上面
React Native 的出现,让前端工程师拥有了使用 JavaScript 编写原生 APP 的能力.相比之前的 Web app 来说,对于性能和用户体验提升了非常多. 但是 React Nati ...
- noip 2003 传染病控制(历史遗留问题2333)
/*codevs 1091 搜索 几个月之前写的70分 今天又写了一遍 并且找到了错误 */ #include<cstdio> #include<vector> #define ...
- CSS3 颜色值HSL表示方式&简单实例
HSL色彩模式:就是色调(Hue).饱和度(Saturation).亮度(Lightness)三个颜色通道的改变以及它们相互之间的叠加来获得各种颜色,色调(Hue)色调最大值360,饱和度和亮度有百分 ...
- Two ways to create file using 'doc'.
Here are two ways to create file using 'doc' command: Method i: copy con [file name][enter key] [con ...
- Node中Exports与module.export的使用与区别
最近在看<node开发实战详解>时有写疑问,所以自己就整理了一些资料.下面是node4.*的官方api文档(http://nodejs.cn/doc/node_4/modules.html ...
- Long型整数,缄默溢出
/** 长整数问题 @author husky */ public class LongDemo { public static void main(String[] args) { /** * 问题 ...
- Android JIN返回结构体
一.对应类型符号 Java 类型 符号 boolean Z byte B char C short S int I long J float ...
- IOS下双击背景, touchmove, 阻止页面背景scroll.
ios prevent dblclick(tap) page scrollhtml add:("minimal-ui" is very important) <meta na ...
- JeeSite试用
JeeSite主要定位于企业信息化领域.网址:http://www.oschina.net/p/jeesite 从描述来看,各种NB,下来看的最主要原因是最近还在更新,觉得有问题可以有一批人一起研究研 ...
- CSS动画:Transform中使用频繁的scale,rotate,translate动画
动画中,skew只是transform中的一种形式的动画,我们还可以学习scale,rotate,translate.这是目前使用比较频繁的属性动作. 1.scale动画的定义:(单位数值) scal ...