.net中压缩和解压缩的处理
最近在网上查了一下在.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中压缩和解压缩的处理的更多相关文章
- iOS中使用ZipArchive压缩和解压缩文件-备
为什么我需要解压缩文件 有许多原因能解释为什么我要在工程中使用压缩和解压缩功能,下面是几个常见的原因: 苹果App Store的50M下载限制 苹 果公司出于流量的考虑,规定在非WIFI环境下,限制用 ...
- 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏
我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...
- Linux下的压缩和解压缩命令——gzip/gunzip
gzip命令 gzip命令用来压缩文件.gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处".gz"扩展名. gzip是在Linux系统中经常使用的一个对文件进行压 ...
- Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)
1.压缩和解压缩命令 常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令 zip 压缩文件名 源文件:压缩文件 ...
- [Java 基础] 使用java.util.zip包压缩和解压缩文件
reference : http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...
- 关于webservice大数据量传输时的压缩和解压缩
当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...
- 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期
[源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...
- IOS开发之网络编程--文件压缩和解压缩
前言: QQ表情包就用到了解压缩,从网络下载的那么多表情文件格式并不是一个一个图片文件,而是多个图片压缩而成的表情压缩包.下面介绍的是iOS开发中会用到的压缩和解压缩的第三方框架的使用. 注意: 这个 ...
- 压缩和解压缩gz包
gz是Linux和OSX中常见的压缩文件格式,下面是用java压缩和解压缩gz包的例子 public class GZIPcompress { public static void FileCompr ...
随机推荐
- 【Android】Android部分问题记录
1.EditText不显示光标 开发的时候遇到有部分手机,小米系列以及华为部分手机不显示光标. 设置EditText属性 android:textCursorDrawable="@null& ...
- 关于offset()的理解
假如要取得x线的offset().top,在页面上的是x线到页面顶端的距离s1,如何取得x线在窗口上的top呢,这就需要取得窗口顶端到页面顶端的距离s2,由于s1和s2都是有方向的,所以,s1-s2就 ...
- LinkedHashSet的实现原理
1. LinkedHashSet概述 LinkedHashSet是具有可预知迭代顺序的Set接口的哈希表和链接列表实现.此实现与HashSet的不同之处在于,后者维护着一个运行于所有条目的双重链接列表 ...
- 【HTML】Intermediate3:Meta Tags
1.Meta tags were the town criers of the Internet Do anything to the content that is presented in the ...
- Java笔记(十八)……包
概述 对类文件进行分类管理. 给类提供多层命名空间. 写在程序文件的第一行. 类名的全称的是 包名.类名. 包也是一种封装形式. 访问权限 引用<The Complete Reference&g ...
- Azure 虚拟机常见问题-下
虚拟机上的默认用户名和密码是什么? Azure 提供的映像没有预先配置用户名和密码.使用这些映像中的其中一个创建虚拟机时,你需要提供用户名和密码,用于登录到虚拟机. 提示 如果忘记了用户名或密码且安装 ...
- JAVA Serialization 序列化
最近在做Android 项目时用到了WebView,可悲的是,在html上有无数用户的操作,而这些操作被JS返回给了Android的内存中,当深层的Activity开启时,之前的Activity很可能 ...
- PL/SQL基础
打印 hi set serveroutput on --打开输出开关 declare --说明部分(变量说明,光标申明或者例外说明) begin --程序 ...
- window下 Mongodb无法访问28107的有关问题(转)
原文链接:http://www.myexception.cn/go/1956868.html Mongodb无法访问28107的问题 0:环境 os:window7 64位 mongodb版本:3.0 ...
- android开源项目学习
FBReaderJ FBReaderJ用于Android平台的电子书阅读器,它支持多种电子书籍格式包括:oeb.ePub和fb2.此外还支持直接读取zip.tar和gzip等压缩文档. 项目地址:ht ...