最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种:

1.利用.net自带的压缩和解压缩方法GZip

参考代码如下:

//========================================================================
// 类名: CommonCompress
/// <summary>
/// 用于对文件和字符串进行压缩
/// </summary>
/// <remarks>
/// 用于对文件和字符串进行压缩
/// </remarks>
/*=======================================================================
变更记录
序号   更新日期  开发者   变更内容
0001   2008/07/22 张 新建
=======================================================================*/
public class CommonCompress
{
/// <summary>
/// 压缩字符串
/// </summary>
/// <param name="strUncompressed">未压缩的字符串</param>
/// <returns>压缩的字符串</returns>
public static string StringCompress(string strUncompressed)
{
byte[] bytData = System.Text.Encoding.Unicode.GetBytes(strUncompressed);
MemoryStream ms = new MemoryStream();
Stream s = new GZipStream(ms, CompressionMode.Compress);
s.Write(bytData, , bytData.Length);
s.Close();
byte[] dataCompressed = (byte[])ms.ToArray();
return System.Convert.ToBase64String(dataCompressed, , dataCompressed.Length);
} /// <summary>
/// 解压缩字符串
/// </summary>
/// <param name="strCompressed">压缩的字符串</param>
/// <returns>未压缩的字符串</returns>
public static string StringDeCompress(string strCompressed)
{
System.Text.StringBuilder strUncompressed = new System.Text.StringBuilder();
int totalLength = ;
byte[] bInput = System.Convert.FromBase64String(strCompressed); ;
byte[] dataWrite = new byte[];
Stream s = new GZipStream(new MemoryStream(bInput), CompressionMode.Decompress);
while (true)
{
int size = s.Read(dataWrite, , dataWrite.Length);
if (size > )
{
totalLength += size;
strUncompressed.Append(System.Text.Encoding.Unicode.GetString(dataWrite, , size));
}
else
{
break;
}
}
s.Close();
return strUncompressed.ToString();
} /// <summary>
/// 压缩文件
/// </summary>
/// <param name="iFile">压缩前文件路径</param>
/// <param name="oFile">压缩后文件路径</param>
public static void CompressFile(string iFile, string oFile)
{
//判断文件是否存在
if (File.Exists(iFile) == false)
{
throw new FileNotFoundException("文件未找到!");
}
//创建文件流
byte[] buffer = null;
FileStream iStream = null;
FileStream oStream = null;
GZipStream cStream = null;
try
{
//把文件写进数组
iStream = new FileStream(iFile, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new byte[iStream.Length];
int num = iStream.Read(buffer, , buffer.Length);
if (num != buffer.Length)
{
throw new ApplicationException("压缩文件异常!");
}
//创建文件输出流并输出
oStream = new FileStream(oFile, FileMode.OpenOrCreate, FileAccess.Write);
cStream = new GZipStream(oStream, CompressionMode.Compress, true);
cStream.Write(buffer, , buffer.Length);
}
finally
{
//关闭流对象
if (iStream != null) iStream.Close();
if (cStream != null) cStream.Close();
if (oStream != null) oStream.Close();
}
} /// <summary>
/// 解压缩文件
/// </summary>
/// <param name="iFile">压缩前文件路径</param>
/// <param name="oFile">压缩后文件路径</param>
public static void DecompressFile(string iFile, string oFile)
{
//判断文件是否存在
if (File.Exists(iFile) == false)
{
throw new FileNotFoundException("文件未找到!");
}
//创建文件流
FileStream iStream = null;
FileStream oStream = null;
GZipStream dStream = null;
byte[] qBuffer = new byte[];
try
{
//把压缩文件写入数组
iStream = new FileStream(iFile, FileMode.Open);
dStream = new GZipStream(iStream, CompressionMode.Decompress, true);
int position = (int)iStream.Length - ;
iStream.Position = position;
iStream.Read(qBuffer, , );
iStream.Position = ;
int num = BitConverter.ToInt32(qBuffer, );
byte[] buffer = new byte[num + ];
int offset = , total = ;
while (true)
{
int bytesRead = dStream.Read(buffer, offset, );
if (bytesRead == ) break;
offset += bytesRead;
total += bytesRead;
}
//创建输出流并输出
oStream = new FileStream(oFile, FileMode.Create);
oStream.Write(buffer, , total);
oStream.Flush();
}
finally
{
//关闭流对象
if (iStream != null) iStream.Close();
if (dStream != null) dStream.Close();
if (oStream != null) oStream.Close();
}
}
}

2.利用ICSharpCode的压缩和解压缩方法,需引用ICSharpCode.SharpZipLib.dll,这个类库是开源的,源码地址http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

参考代码如下:

using System;
using System.Collections.Generic;
using System.IO; using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums; namespace ZYBNET.FW.Utility.CommonMethod
{
//========================================================================
// 类名: ZipHelper
/// <summary>
/// 用于对文件和字符串进行压缩
/// </summary>
/// <remarks>
/// 用于对文件和字符串进行压缩
/// </remarks>
/*=======================================================================
变更记录
序号   更新日期  开发者   变更内容
0001   2008/07/22 张 新建
=======================================================================*/
public class ZipHelper
{
#region 压缩文件夹,支持递归
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="dir">待压缩的文件夹</param>
/// <param name="targetFileName">压缩后文件路径(包括文件名)</param>
/// <param name="recursive">是否递归压缩</param>
/// <returns></returns>
public static bool Compress(string dir, string targetFileName, bool recursive)
{
//如果已经存在目标文件,询问用户是否覆盖
if (File.Exists(targetFileName))
{
throw new Exception("同名文件已经存在!");
}
string[] ars = new string[];
if (recursive == false)
{
ars[] = dir;
ars[] = targetFileName;
return ZipFileDictory(ars);
} FileStream zipFile;
ZipOutputStream zipStream; //打开压缩文件流
zipFile = File.Create(targetFileName);
zipStream = new ZipOutputStream(zipFile); if (dir != String.Empty)
{
CompressFolder(dir, zipStream, dir);
} //关闭压缩文件流
zipStream.Finish();
zipStream.Close(); if (File.Exists(targetFileName))
return true;
else
return false;
} /// <summary>
/// 压缩目录
/// </summary>
/// <param name="args">数组(数组[0]: 要压缩的目录; 数组[1]: 压缩的文件名)</param>
public static bool ZipFileDictory(string[] args)
{
ZipOutputStream zStream = null;
try
{
string[] filenames = Directory.GetFiles(args[]);
Crc32 crc = new Crc32();
zStream = new ZipOutputStream(File.Create(args[]));
zStream.SetLevel();
//循环压缩文件夹中的文件
foreach (string file in filenames)
{
//打开压缩文件
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
ZipEntry entry = new ZipEntry(file);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zStream.PutNextEntry(entry);
zStream.Write(buffer, , buffer.Length);
}
}
catch
{
throw;
}
finally
{
zStream.Finish();
zStream.Close();
}
return true;
} /// <summary>
/// 压缩某个子文件夹
/// </summary>
/// <param name="basePath">待压缩路径</param>
/// <param name="zips">压缩文件流</param>
/// <param name="zipfolername">待压缩根路径</param>
private static void CompressFolder(string basePath, ZipOutputStream zips, string zipfolername)
{
if (File.Exists(basePath))
{
AddFile(basePath, zips, zipfolername);
return;
}
string[] names = Directory.GetFiles(basePath);
foreach (string fileName in names)
{
AddFile(fileName, zips, zipfolername);
} names = Directory.GetDirectories(basePath);
foreach (string folderName in names)
{
CompressFolder(folderName, zips, zipfolername);
} } /// <summary>
/// 压缩某个子文件
/// </summary>
/// <param name="fileName">待压缩文件</param>
/// <param name="zips">压缩流</param>
/// <param name="zipfolername">待压缩根路径</param>
private static void AddFile(string fileName, ZipOutputStream zips, string zipfolername)
{
if (File.Exists(fileName))
{
CreateZipFile(fileName, zips, zipfolername);
}
} /// <summary>
/// 压缩单独文件
/// </summary>
/// <param name="FileToZip">待压缩文件</param>
/// <param name="zips">压缩流</param>
/// <param name="zipfolername">待压缩根路径</param>
private static void CreateZipFile(string FileToZip, ZipOutputStream zips, string zipfolername)
{
try
{
FileStream StreamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read);
string temp = FileToZip;
string temp1 = zipfolername;
if (temp1.Length > )
{
temp = temp.Replace(zipfolername + "\\", "");
}
ZipEntry ZipEn = new ZipEntry(temp); zips.PutNextEntry(ZipEn);
byte[] buffer = new byte[];
System.Int32 size = StreamToZip.Read(buffer, , buffer.Length);
zips.Write(buffer, , size);
try
{
while (size < StreamToZip.Length)
{
int sizeRead = StreamToZip.Read(buffer, , buffer.Length);
zips.Write(buffer, , sizeRead);
size += sizeRead;
}
}
catch (System.Exception ex)
{
throw ex;
} StreamToZip.Close();
}
catch
{
throw;
}
}
#endregion #region 解压缩
/// <summary>
/// 功能:解压zip格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <returns>解压是否成功</returns>
public static void UnZipFile(string zipFilePath, string unZipDir)
{ if (zipFilePath == string.Empty)
{
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath))
{
throw new Exception("压缩文件不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("//"))
unZipDir += "//";
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir); try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName.Length > )
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (!directoryName.EndsWith("//"))
directoryName += "//";
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
}
}
}
}
}
catch
{
throw;
}
}
#endregion }
}

3.利用java的压缩和解压缩方法,需引用vjslib.dll

至于这种方法的使用,大家可以去查阅msdn,这里就不写了

4.利用zlibwapi.dll的API进行压缩

据说压缩效率比较好,但是在网上没找到供下载的链接,有兴趣的朋友可以试试

5.使用System.IO.Packaging压缩和解压

System.IO.Packaging在WindowsBase.dll程序集下,使用时需要添加对WindowsBase的引用

/// <summary>
/// Add a folder along with its subfolders to a Package
/// </summary>
/// <param name="folderName">The folder to add</param>
/// <param name="compressedFileName">The package to create</param>
/// <param name="overrideExisting">Override exsisitng files</param>
/// <returns></returns>
static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
{
if (folderName.EndsWith(@"\"))
folderName = folderName.Remove(folderName.Length - );
bool result = false;
if (!Directory.Exists(folderName))
{
return result;
} if (!overrideExisting && File.Exists(compressedFileName))
{
return result;
}
try
{
using (Package package = Package.Open(compressedFileName, FileMode.Create))
{
var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
foreach (string fileName in fileList)
{ //The path in the package is all of the subfolders after folderName
string pathInPackage;
pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName); Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(packagePartDocument.GetStream());
}
}
}
result = true;
}
catch (Exception e)
{
throw new Exception("Error zipping folder " + folderName, e);
} return result;
} /// <summary>
/// Compress a file into a ZIP archive as the container store
/// </summary>
/// <param name="fileName">The file to compress</param>
/// <param name="compressedFileName">The archive file</param>
/// <param name="overrideExisting">override existing file</param>
/// <returns></returns>
static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting)
{
bool result = false; if (!File.Exists(fileName))
{
return result;
} if (!overrideExisting && File.Exists(compressedFileName))
{
return result;
} try
{
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative)); using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate))
{
if (package.PartExists(partUriDocument))
{
package.DeletePart(partUriDocument);
} PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(packagePartDocument.GetStream());
}
}
result = true;
}
catch (Exception e)
{
throw new Exception("Error zipping file " + fileName, e);
} return result;
} } 、zip文件解压 Code/// <summary>
/// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification
/// </summary>
/// <param name="folderName">The folder to extract the package to</param>
/// <param name="compressedFileName">The package file</param>
/// <param name="overrideExisting">override existing files</param>
/// <returns></returns>
static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting)
{
bool result = false;
try
{
if (!File.Exists(compressedFileName))
{
return result;
} DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
if (!directoryInfo.Exists)
directoryInfo.Create(); using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart packagePart in package.GetParts())
{
ExtractPart(packagePart, folderName, overrideExisting);
}
} result = true;
}
catch (Exception e)
{
throw new Exception("Error unzipping file " + compressedFileName, e);
} return result;
} static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
{
string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/'); if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
Directory.CreateDirectory(Path.GetDirectoryName(stringPart)); if (!overrideExisting && File.Exists(stringPart))
return;
using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
{
packagePart.GetStream().CopyTo(fileStream);
}
}

.net中压缩和解压缩的处理的更多相关文章

  1. iOS中使用ZipArchive压缩和解压缩文件-备

    为什么我需要解压缩文件 有许多原因能解释为什么我要在工程中使用压缩和解压缩功能,下面是几个常见的原因: 苹果App Store的50M下载限制 苹 果公司出于流量的考虑,规定在非WIFI环境下,限制用 ...

  2. 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏

    我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...

  3. Linux下的压缩和解压缩命令——gzip/gunzip

    gzip命令 gzip命令用来压缩文件.gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处".gz"扩展名. gzip是在Linux系统中经常使用的一个对文件进行压 ...

  4. Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)

    1.压缩和解压缩命令    常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令        zip 压缩文件名 源文件:压缩文件   ...

  5. [Java 基础] 使用java.util.zip包压缩和解压缩文件

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

  6. 关于webservice大数据量传输时的压缩和解压缩

    当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...

  7. 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期

    [源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...

  8. IOS开发之网络编程--文件压缩和解压缩

    前言: QQ表情包就用到了解压缩,从网络下载的那么多表情文件格式并不是一个一个图片文件,而是多个图片压缩而成的表情压缩包.下面介绍的是iOS开发中会用到的压缩和解压缩的第三方框架的使用. 注意: 这个 ...

  9. 压缩和解压缩gz包

    gz是Linux和OSX中常见的压缩文件格式,下面是用java压缩和解压缩gz包的例子 public class GZIPcompress { public static void FileCompr ...

随机推荐

  1. POJ2492 A Bug's Life 带权并查集

    分析:所谓带权并查集,就是比朴素的并查集多了一个数组,记录一些东西,例如到根的距离,或者和根的关系等 这个题,权数组为relation 代表的关系  1 和父节点不同性别,0,和父节点同性别 并查集一 ...

  2. [转]ASP.NET MVC 入门11、使用AJAX

    在ASP.NET MVC beta发布之前,M$就宣布支持开源的JS框架jQuery,然后ASP.NET MVC beta发布后,你建立一个ASP.NET MVC beta的项目后,你可以在项目的sc ...

  3. Specular light 计算

    Specular lighting is most commonly used to give light reflection off of metallic surfaces such as mi ...

  4. java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0 *&* 解决方法

    java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0*&*^    at java. ...

  5. HTML 网页游戏 2048

    新手只会一点html和css,javascript基本不会,更别提jQuery了= = 跟着慕课网的教学视频(视频地址:http://www.imooc.com/learn/76)一点点做的,由于自己 ...

  6. oralce health monitor

    1. Health Monitor简介    Health Monitor是11g里新增加的特性,用于数据库的各层和各个组建的诊断检查.例如可以检查:文件损坏.物理逻辑块损坏.redo和undo故障. ...

  7. 对XML和YAML文件实现I/O操作

    1.文件的打开关闭 XML\YAML文件在OpenCV中的数据结构为FileStorage,打开操作例如: string filename = "I.xml"; FileStora ...

  8. 立体视觉-opencv中立体匹配相关代码

    三种匹配算法比较 BM算法: 该算法代码: view plaincopy to clipboardprint? CvStereoBMState *BMState = cvCreateStereoBMS ...

  9. JBPM学习(六):详解流程图

    概念: 流程图的组成: a. 活动 Activity / 节点 Node b. 流转 Transition / 连线(单向箭头) c. 事件 1.流转(Transition) a) 一般情况一个活动中 ...

  10. FrankFan7你问我答之一

    作者:范军 (Frank Fan) 新浪微博:@frankfan7   微信:frankfan7 最近网友留言很多,你既然看得起我问了,我就说说个人浅见.看看就行了,也别认真. Q:你具体工作是什么? ...