SharpZipLib提供了多种压缩算法的支持,纯csharp代码,参见
http://www.icsharpcode.net/OpenSource/SharpZipLib/default.asp,你可以到其官方网站下载最新版本的SharpZipLib:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.asp。
该控件是使用csharp写的,因此可以直接在dotnet环境中引用,不需要注册。
利用 SharpZipLib方便地压缩和解压缩文件
最新版本的SharpZipLib(0.84)增加了很多新的功能,其中包括增加了FastZip类,这让我们可以非常方便地把一个目录压缩成一个压缩包,经测试可以很好地支持文件中包含中文以及空格的情况。
将下面的两个方法添加到类中,然后直接调用:
压缩:
/// Create a Zip archive.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="directory">The directory to Zip.</param>
public static void PackFiles( string filename, string directory)
... {
try
...{
FastZip fz = new FastZip();
fz.CreateEmptyDirectories = true;
fz.CreateZip(filename, directory, true, "");
fz = null;
}
catch (Exception)
...{
throw;
}
}
解压缩:
/// <summary>
/// Unpacks the files.
/// </summary>
/// <param name="file">The file.</param>
/// <returns>if succeed return true,otherwise false.</returns>
public static bool UnpackFiles(string file, string dir)
{
try
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
ZipInputStream s = new ZipInputStream(File.OpenRead(file));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName != String.Empty)
Directory.CreateDirectory(dir + directoryName);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(dir + 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;
}
}
streamWriter.Close();
}
}
s.Close();
return true;
}
catch (Exception)
{
throw;
}
}
添加引用:
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
调用方式如下:
假如建立了一个Pack类,在你的代码中添加:
Pack.PackFiles(file,directory); //Zip file是你要生成的压缩文件,directory是要压缩的目录,支持子目录。
Pack.UnpackFiles(file,dir); //UnZip file是要解压缩的文件,dir是解压路径
SharpZipLib的功能很强大,上面只是实现了简单的压缩、解压,具体的方法还是自己研究。