ASP.NET 文件压缩解压类(文件压缩解压类(C#))
主要为大家详细介绍了ASP.NET 文件压缩解压类,感兴趣的小伙伴们可以参考一下
本文实例讲述了asp.net C#实现解压缩文件的方法,需要引用一个ICSharpCode.SharpZipLib.dll,供大家参考,具体如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using System.Web;
namespace Mvc51Hiring.Common.Tool
{
/// <summary> <br> /// 作者:来自网格<br> /// 修改人:sunkaixaun
/// 压缩和解压文件
/// </summary>
public class ZipClass
{
/// <summary>
/// 所有文件缓存
/// </summary>
List<string> files = new List<string>();
/// <summary>
/// 所有空目录缓存
/// </summary>
List<string> paths = new List<string>();
/// <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, int blockSize)
{
if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
{
throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
}
FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
FileStream zipFile = File.Create(zipedFile);
ZipOutputStream zipStream = new ZipOutputStream(zipFile);
ZipEntry zipEntry = new ZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
int 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 (Exception ex)
{
GC.Collect();
throw ex;
}
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
GC.Collect();
}
/// <summary>
/// 压缩目录(包括子目录及所有文件)
/// </summary>
/// <param name="rootPath">要压缩的根目录</param>
/// <param name="destinationPath">保存路径</param>
/// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)