ICSharpCode.SharpZipLib.dll 是一个开源的组件,提供了多种压缩算法的支持,可以利用它对多种文件格式进行压缩与解压缩。
下载网址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
在项目中加入对ICSharpCode.SharpZipLib.dll的引用:
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="savePath">保存压缩包的路径</param>
/// <param name="fileNames">要压缩的文件名</param>
public static void CompressFile(string savePath, params string[] fileNames)
{
ZipOutputStream stream = new ZipOutputStream(File.Create(savePath));
stream.SetLevel(8);//设置压缩级别(0-9),值越大压缩越厉害
//遍历所有要压缩的文件
foreach (string fileName in fileNames)
{
if (File.Exists(fileName))
{
FileStream fs = File.OpenRead(fileName);
byte[] buffer = new byte[fs.Length];//设置缓冲区大小
int size = fs.Read(buffer, 0, buffer.Length); //读入缓冲区中的字节数
string entryName = fileName.Substring(fileName.LastIndexOf("//") + 1);
ZipEntry entry = new ZipEntry(entryName);
stream.PutNextEntry(entry);
stream.Write(buffer, 0, size);
try
{
//如果读入缓冲区中的字节数没有所请求的总字节数那么多
while (size < fs.Length)
{
int sizeRead = fs.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
catch (Exception ex) { throw ex; }
finally { fs.Close(); }
}
}
stream.Finish();
stream.Close();
}
/// <summary>
/// 解压缩文件
/// </summary>
/// <param name="packPath">压缩包路径</param>
/// <param name="saveDir">文件保存目录</param>
public static void DecompressFile(string packPath, string saveDir)
{
//目录不存在则创建
if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
int size = 2048;
byte[] buffer = new byte[size];
ZipInputStream stream = new ZipInputStream(File.OpenRead(packPath));
//解压文件到指定的目录
try
{
ZipEntry entry;
while ((entry = stream.GetNextEntry()) != null)
{
FileStream fs = File.Create(saveDir +new Random().Next(100)+ entry.Name);
while (true)
{
size = stream.Read(buffer, 0, buffer.Length);
if (size <= 0) break; //读到压缩文件尾
fs.Write(buffer, 0, size);
}
fs.Close();
}
}
catch (Exception ex) { throw ex; }
stream.Close();
}