用了第二种方法,感觉很不错,其他都没用过了。摘录下来,做一个备忘。

最近在网上查了一下在.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);
}
}

原文网址:http://blog.csdn.net/fhzh520/article/details/1491900

C#- 压缩和解压缩的研究 .的更多相关文章

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

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

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

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

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

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

  4. C#利用SharpZipLib进行文件的压缩和解压缩

    我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net下载了关于压缩和解压缩的源码,但是下载下来后,面对这么多的代码,一时不知如何下手.只好耐下心来, ...

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. BZOJ 4005 [JLOI 2015] 骗我呢

    首先,我们可以得到:每一行的数都是互不相同的,所以每一行都会有且仅有一个在 $[0, m]$ 的数没有出现. 我们可以考虑设 $Dp[i][j]$ 为处理完倒数 $i$ 行,倒数第 $i$ 行缺的数字 ...

  2. Linux +apache+fastcgi运行c/c++

    在Linux上搭建apache+fastcgi环境,说多了都是泪啊. 花费我几天时间,开源软件虽说好用,但是版本众多,文档缺乏,什么都只能自己摸索. 终于成功运行起来,特此记录. 一. apache ...

  3. 如何查看Linux的磁盘空间还有多少

    无论是Linux还是unix,都提供了很多工具来查看磁盘空间的大小. 1. df命令,df命令,可以查看当前文件系统占用的空间的大小,以及剩余的大小,如下例子: Filesystem     1K-b ...

  4. Java中堆和栈创建对象的区别

    http://blog.csdn.net/hbhhww/article/details/8152838

  5. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)

    一.redirect为什么会丢数据? when a handler method completes, any model data specified in the method is copied ...

  6. 第十章Composite设备

    10.1 Composite设备介绍 USB的Composite类是USB 复合设备类,一个USB设备具有多种设备功能,比如一个USB设备同时具有鼠标和键盘功能.单一的USB设备开发相对简单,但在很多 ...

  7. 169. Majority Element

    题目: Given an array of size n, find the majority element. The majority element is the element that ap ...

  8. 解决“重新安装vmware-tools”灰色而无法安装的问题

    前几天重装系统,之后虚拟机需要重新装,装好后要使用vmware-tools实现文件共享,却发现虚拟机那里显示为灰色的,无法安装vmware-tools,在共享文件夹那里设置好共享的文件夹猴也没有用,/ ...

  9. Android开发UI之布局文件LinearLayout

    LinearLayout-线性布局,该布局中的控件按照水平方向排列或者竖直方向排列. 通过属性android:orientation=""决定的,可选值:vertical和hori ...

  10. 利用switch case判断是今天的第多少天

    static void Main(string[] args)        {            while (true)            {                int m1 ...