今天過中秋節,當地時間(2013-09-08),公司也放假了,正好也閒着沒事,就在網上學習學習,找找資料什麼的。
最近項目上可能會用到壓縮的功能,因此本身就先在網上學習了,發現一個不錯的用於壓縮的DLL文件,而且免費,並且開放源碼;
這就是我今天介紹的對象:html
SharpZipLib
咱們先看看它的官方介紹吧:算法
#ziplib (SharpZipLib, formerly NZipLib) is a Zip, GZip, Tar and BZip2 library written entirely in C# for the .NET platform. It is implemented as an assembly (installable in the GAC), and thus can easily be incorporated into other projects (in any .NET language). The creator of #ziplib put it this way: "I've ported the zip library over to C# because I needed gzip/zip compression and I didn't want to use libzip.dll or something like this. I want all in pure C#."c#
Download
- Assemblies for .NET 1.1, .NET 2.0 (3.5, 4.0), .NET CF 1.0, .NET CF 2.0: Download 237 KB
- Source code and samples Download 708 KB
- Help file Download 1208 KB
All downloads are for version 0.86.0, built on 2010/05/25.數組
以上是從官方網站截取的部分說明,根據當前時間2014/09/08(中秋節),能夠看到目前官方發佈的版本號是0.86.0根據沒有時間給你們報道。
這裏下載:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
源代碼:http://www.icsharpcode.net/OpenSource/SharpZipLib/DownloadLatestVersion.asp?what=sourcesamples
修改記錄:http://wiki.sharpdevelop.net/default.aspx/SharpZipLib.ReleaseHistory
SharpZipLib的許但是通過修改的GPL,底線是容許用在不開源商業軟件中,意思就是無償使用。緩存
以上參考網站:http://unruledboy.cnblogs.com/archive/2005/08/05/SharpZipLib084.html函數
====================================================================================post
添加引用ICSharpCode.SharpZipLib.dll學習
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using ICSharpCode.SharpZipLib.Zip;
namespace Lib
{
///
/// 文件壓縮、解壓縮
///
public class FileCompression
{
///
/// 構造函數
///
public FileCompression()
{
}
#region 加密、壓縮文件
///
/// 壓縮文件
///
/// <param name="fileNames">要打包的文件列表
/// <param name="GzipFileName">目標文件名
/// <param name="CompressionLevel">壓縮品質級別(0~9)
/// <param name="SleepTimer">休眠時間(單位毫秒)
public static void Compress(List fileNames, string GzipFileName, int CompressionLevel, int SleepTimer)
{
ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
try
{
s.SetLevel(CompressionLevel); //0 - store only to 9 - means best compression
foreach (FileInfo file in fileNames)
{
FileStream fs = null;
try
{
fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
}
catch
{ continue; }
// 方法二,將文件分批讀入緩衝區
byte[] data = new byte[2048];
int size = 2048;
ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
s.PutNextEntry(entry);
while (true)
{
size = fs.Read(data, 0, size);
if (size <= 0) break;
s.Write(data, 0, size);
}
fs.Close();
file.Delete();
Thread.Sleep(SleepTimer);
}
}
finally
{
s.Finish();
s.Close();
}
}
#endregion
#region 解密、解壓縮文件
///
/// 解壓縮文件
///
/// <param name="GzipFile">壓縮包文件名
/// <param name="targetPath">解壓縮目標路徑
public static void Decompress(string GzipFile, string targetPath)
{
//string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";
string directoryName = targetPath;
if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解壓目錄
string CurrentDirectory = directoryName;
byte[] data = new byte[2048];
int size = 2048;
ZipEntry theEntry = null;
using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
{
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{// 該結點是目錄
if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
}
else
{
if (theEntry.Name != String.Empty)
{
//解壓文件到指定的目錄
using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
{
while (true)
{
size = s.Read(data, 0, data.Length);
if (size <= 0) break;
streamWriter.Write(data, 0, size);
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}
#endregion
}
}
以上參考出處: .Net 下利用ICSharpCode.SharpZipLib.dll實現文件壓縮、解壓縮測試
====================================================================================網站
1、使用ICSharpCode.SharpZipLib.dll;
下載地址 http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
2、壓縮算法介紹:
基於(ICSharpCode.SharpZipLib.dll)的文件壓縮方法,類文件
程序代碼----壓縮文件:
using System;
using System.IO;
using System.Collections;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
namespace FileCompress
{
/// <summary>
/// 功能:壓縮文件
/// creator chaodongwang 2009-11-11
/// </summary>
public class ZipClass
{
/// <summary>
/// 壓縮單個文件
/// </summary>
/// <param name="FileToZip">被壓縮的文件名稱(包含文件路徑)</param>
/// <param name="ZipedFile">壓縮後的文件名稱(包含文件路徑)</param>
/// <param name="CompressionLevel">壓縮率0(無壓縮)-9(壓縮率最高)</param>
/// <param name="BlockSize">緩存大小</param>
public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel)
{
//若是文件沒有找到,則報錯
if (!System.IO.File.Exists(FileToZip))
{
throw new System.IO.FileNotFoundException("文件:" + FileToZip + "沒有找到!");
}
if (ZipedFile == string.Empty)
{
ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) + ".zip";
}
if (Path.GetExtension(ZipedFile) != ".zip")
{
ZipedFile = ZipedFile + ".zip";
}
////若是指定位置目錄不存在,建立該目錄
//string zipedDir = ZipedFile.Substring(0,ZipedFile.LastIndexOf("//"));
//if (!Directory.Exists(zipedDir))
// Directory.CreateDirectory(zipedDir);
//被壓縮文件名稱
string filename = FileToZip.Substring(FileToZip.LastIndexOf('//') + 1);
System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
ZipEntry ZipEntry = new ZipEntry(filename);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(CompressionLevel);
byte[] buffer = new byte[2048];
System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, size);
try
{
while (size < StreamToZip.Length)
{
int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ZipStream.Finish();
ZipStream.Close();
StreamToZip.Close();
}
}
/// <summary>
/// 壓縮文件夾的方法
/// </summary>
public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel)
{
//壓縮文件爲空時默認與壓縮文件夾同一級目錄
if (ZipedFile == string.Empty)
{
ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("//") + 1);
ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("//")) +"//"+ ZipedFile+".zip";
}
if (Path.GetExtension(ZipedFile) != ".zip")
{
ZipedFile = ZipedFile + ".zip";
}
using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile)))
{
zipoutputstream.SetLevel(CompressionLevel);
Crc32 crc = new Crc32();
Hashtable fileList = getAllFies(DirToZip);
foreach (DictionaryEntry item in fileList)
{
FileStream fs = File.OpenRead(item.Key.ToString());
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length + 1));
entry.DateTime = (DateTime)item.Value;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, 0, buffer.Length);
}
}
}
/// <summary>
/// 獲取全部文件
/// </summary>
/// <returns></returns>
private Hashtable getAllFies(string dir)
{
Hashtable FilesList = new Hashtable();
DirectoryInfo fileDire = new DirectoryInfo(dir);
if (!fileDire.Exists)
{
throw new System.IO.FileNotFoundException("目錄:" + fileDire.FullName + "沒有找到!");
}
this.getAllDirFiles(fileDire, FilesList);
this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
return FilesList;
}
/// <summary>
/// 獲取一個文件夾下的全部文件夾裏的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
this.getAllDirsFiles(dir.GetDirectories(), filesList);
}
}
/// <summary>
/// 獲取一個文件夾下的文件
/// </summary>
/// <param name="strDirName">目錄名稱</param>
/// <param name="filesList">文件列表HastTable</param>
private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
}
}
}
程序代碼----解壓文件
using System;
using System.Collections.Generic;
/// <summary>
/// 解壓文件
/// </summary>
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace FileCompress
{
/// <summary>
/// 功能:解壓文件
/// creator chaodongwang 2009-11-11
/// </summary>
public class UnZipClass
{
/// <summary>
/// 功能:解壓zip格式的文件。
/// </summary>
/// <param name="zipFilePath">壓縮文件路徑</param>
/// <param name="unZipDir">解壓文件存放路徑,爲空時默認與壓縮文件同一級目錄下,跟壓縮文件同名的文件夾</param>
/// <param name="err">出錯信息</param>
/// <returns>解壓是否成功</returns>
public void UnZip(string zipFilePath, string unZipDir)
{
if (zipFilePath == string.Empty)
{
throw new Exception("壓縮文件不能爲空!");
}
if (!File.Exists(zipFilePath))
{
throw new System.IO.FileNotFoundException("壓縮文件不存在!");
}
//解壓文件夾爲空時默認與壓縮文件同一級目錄下,跟壓縮文件同名的文件夾
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("//"))
unZipDir += "//";
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
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 > 0)
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (!directoryName.EndsWith("//"))
directoryName += "//";
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
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;
}
}
}
}
}
}
}
}
}
s.net(c#.net)實例下載 :/Files/chaodongwang/FileCompress.rar
轉自:http://www.cnblogs.com/chaodongwang/archive/2009/11/11/1600821.html
出處參考:http://blog.csdn.net/paolei/article/details/5405423
====================================================================================
ZipLib組件與.net自帶的Copression比較,在壓縮方面更勝一籌,通過BZip2壓縮要小不少,親手測試,不信你也能夠試一試。並且這個功能更增強大。下面就是我的作的一個小例子,具體的應用程序源碼: /Files/yank/Compress.rar。
using System;
using System.Data;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
/// <summary>
/// Summary description for ICSharp
/// </summary>
public class ICSharp
{
public ICSharp()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 壓縮
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public string Compress(string param)
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
//byte[] data = Convert.FromBase64String(param);
MemoryStream ms = new MemoryStream();
Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
try
{
stream.Write(data, 0, data.Length);
}
finally
{
stream.Close();
ms.Close();
}
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// 解壓
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public string Decompress(string param)
{
string commonString="";
byte[] buffer=Convert.FromBase64String(param);
MemoryStream ms = new MemoryStream(buffer);
Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
//這裏要指明要讀入的格式,要不就有亂碼
StreamReader reader = new StreamReader(sm,System.Text.Encoding.UTF8);
try
{
commonString=reader.ReadToEnd();
}
finally
{
sm.Close();
ms.Close();
}
return commonString;
}
}
Encoding.UTF8與Convert.FromBase64String
Encoding.UTF8 屬性
獲取 UTF-8 格式的編碼。
Unicode 標準爲全部支持腳本中的每一個字符分配一個碼位(一個數字)。Unicode 轉換格式 (UTF) 是一種碼位編碼方式。Unicode 標準 3.2 版使用下列 UTF:
UTF-8,它將每一個碼位表示爲一個由 1 至 4 個字節組成的序列。
UTF-16,它將每一個碼位表示爲一個由 1 至 2 個 16 位整數組成的序列。
UTF-32,它將每一個碼位表示爲一個 32 位整數。
Convert.FromBase64String 方法
將指定的
String(它將二進制數據編碼爲 base 64 數字)轉換成等效的 8 位無符號整數數組。
它的參數也又必定的要求:
參數是 由基 64 數字、空白字符和尾隨填充字符組成。從零開始以升序排列的以 64 爲基的數字爲大寫字符「A」到「Z」、小寫字符「a」到「z」、數字「0」到「9」以及符號「+」和「/」。空白字符爲 Tab、空格、回車和換行。s 中能夠出現任意數目的空白字符,由於全部空白字符都將被忽略。無值字符「=」用於尾部的空白。s 的末尾能夠包含零個、一個或兩個填充字符。
異常:
s 的長度(忽略空白字符)不是 4 的偶數倍。
以上參考出處:http://www.cnblogs.com/yank/archive/2007/11/21/967515.html