ASP.NET 文件压缩解压类(C#)
本文实例讲述了asp.netC#实现解压缩文件的方法,需要引用一个ICSharpCode.SharpZipLib.dll,供大家参考,具体如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingICSharpCode.SharpZipLib.Zip;
usingSystem.IO;
usingICSharpCode.SharpZipLib.Checksums;
usingSystem.Web;
namespaceMvc51Hiring.Common.Tool
{
///<summary><br>///作者:来自网格<br>///修改人:sunkaixaun
///压缩和解压文件
///</summary>
publicclassZipClass
{
///<summary>
///所有文件缓存
///</summary>
List<string>files=newList<string>();
///<summary>
///所有空目录缓存
///</summary>
List<string>paths=newList<string>();
///<summary>
///压缩单个文件根据文件地址
///</summary>
///<paramname="fileToZip">要压缩的文件</param>
///<paramname="zipedFile">压缩后的文件全名</param>
///<paramname="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
///<paramname="blockSize">分块大小</param>
publicvoidZipFile(stringfileToZip,stringzipedFile,intcompressionLevel,intblockSize)
{
if(!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
{
thrownewFileNotFoundException("Thespecifiedfile"+fileToZip+"couldnotbefound.Zippingaborderd");
}
FileStreamstreamToZip=newFileStream(fileToZip,FileMode.Open,FileAccess.Read);
FileStreamzipFile=File.Create(zipedFile);
ZipOutputStreamzipStream=newZipOutputStream(zipFile);
ZipEntryzipEntry=newZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
byte[]buffer=newbyte[blockSize];
intsize=streamToZip.Read(buffer,0,buffer.Length);
zipStream.Write(buffer,0,size);
try
{
while(size<streamToZip.Length)
{
intsizeRead=streamToZip.Read(buffer,0,buffer.Length);
zipStream.Write(buffer,0,sizeRead);
size+=sizeRead;
}
}
catch(Exceptionex)
{
GC.Collect();
throwex;
}
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
GC.Collect();
}
///<summary>
///压缩目录(包括子目录及所有文件)
///</summary>
///<paramname="rootPath">要压缩的根目录</param>
///<paramname="destinationPath">保存路径</param>
///<paramname="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
publicvoidZipFileFromDirectory(stringrootPath,stringdestinationPath,intcompressLevel)
{
GetAllDirectories(rootPath);
/*while(rootPath.LastIndexOf("\\")+1==rootPath.Length)//检查路径是否以"\"结尾
{
rootPath=rootPath.Substring(0,rootPath.Length-1);//如果是则去掉末尾的"\"
}
*/
//stringrootMark=rootPath.Substring(0,rootPath.LastIndexOf("\\")+1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
stringrootMark=rootPath+"\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
Crc32crc=newCrc32();
ZipOutputStreamoutPutStream=newZipOutputStream(File.Create(destinationPath));
outPutStream.SetLevel(compressLevel);//0-storeonlyto9-meansbestcompression
foreach(stringfileinfiles)
{
FileStreamfileStream=File.OpenRead(file);//打开压缩文件
byte[]buffer=newbyte[fileStream.Length];
fileStream.Read(buffer,0,buffer.Length);
ZipEntryentry=newZipEntry(file.Replace(rootMark,string.Empty));
entry.DateTime=DateTime.Now;
//setSizeandthecrc,becausetheinformation
//aboutthesizeandcrcshouldbestoredintheheader
//ifitisnotsetitisautomaticallywritteninthefooter.
//(inthiscasesize==crc==-1intheheader)
//SomeZIPprogramshaveproblemswithzipfilesthatdon'tstore
//thesizeandcrcintheheader.
entry.Size=fileStream.Length;
fileStream.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc=crc.Value;
outPutStream.PutNextEntry(entry);
outPutStream.Write(buffer,0,buffer.Length);
}
this.files.Clear();
foreach(stringemptyPathinpaths)
{
ZipEntryentry=newZipEntry(emptyPath.Replace(rootMark,string.Empty)+"/");
outPutStream.PutNextEntry(entry);
}
this.paths.Clear();
outPutStream.Finish();
outPutStream.Close();
GC.Collect();
}
///<summary>
///多文件打包下载
///</summary>
publicvoidDwonloadZip(string[]filePathList,stringzipName)
{
MemoryStreamms=newMemoryStream();
byte[]buffer=null;
varcontext=HttpContext.Current;
using(ICSharpCode.SharpZipLib.Zip.ZipFilefile=ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))
{
file.BeginUpdate();
file.NameTransform=newMyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
foreach(varitinfilePathList)
{
file.Add(context.Server.MapPath(it));
}
file.CommitUpdate();
buffer=newbyte[ms.Length];
ms.Position=0;
ms.Read(buffer,0,buffer.Length);
}
context.Response.AddHeader("content-disposition","attachment;filename="+zipName);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.End();
}
///<summary>
///取得目录下所有文件及文件夹,分别存入files及paths
///</summary>
///<paramname="rootPath">根目录</param>
privatevoidGetAllDirectories(stringrootPath)
{
string[]subPaths=Directory.GetDirectories(rootPath);//得到所有子目录
foreach(stringpathinsubPaths)
{
GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
}
string[]files=Directory.GetFiles(rootPath);
foreach(stringfileinfiles)
{
this.files.Add(file);//将当前目录中的所有文件全名存入文件List
}
if(subPaths.Length==files.Length&&files.Length==0)//如果是空目录
{
this.paths.Add(rootPath);//记录空目录
}
}
///<summary>
///解压缩文件(压缩文件中含有子目录)
///</summary>
///<paramname="zipfilepath">待解压缩的文件路径</param>
///<paramname="unzippath">解压缩到指定目录</param>
///<returns>解压后的文件列表</returns>
publicList<string>UnZip(stringzipfilepath,stringunzippath)
{
//解压出来的文件列表
List<string>unzipFiles=newList<string>();
//检查输出目录是否以“\\”结尾
if(unzippath.EndsWith("\\")==false||unzippath.EndsWith(":\\")==false)
{
unzippath+="\\";
}
ZipInputStreams=newZipInputStream(File.OpenRead(zipfilepath));
ZipEntrytheEntry;
while((theEntry=s.GetNextEntry())!=null)
{
stringdirectoryName=Path.GetDirectoryName(unzippath);
stringfileName=Path.GetFileName(theEntry.Name);
//生成解压目录【用户解压到硬盘根目录时,不需要创建】
if(!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(directoryName);
}
if(fileName!=String.Empty)
{
//如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
if(theEntry.CompressedSize==0)
break;
//解压文件到指定的目录
directoryName=Path.GetDirectoryName(unzippath+theEntry.Name);
//建立下面的目录和子目录
Directory.CreateDirectory(directoryName);
//记录导出的文件
unzipFiles.Add(unzippath+theEntry.Name);
FileStreamstreamWriter=File.Create(unzippath+theEntry.Name);
intsize=2048;
byte[]data=newbyte[2048];
while(true)
{
size=s.Read(data,0,data.Length);
if(size>0)
{
streamWriter.Write(data,0,size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
GC.Collect();
returnunzipFiles;
}
}
publicclassMyNameTransfom:ICSharpCode.SharpZipLib.Core.INameTransform
{
#regionINameTransform成员
publicstringTransformDirectory(stringname)
{
returnnull;
}
publicstringTransformFile(stringname)
{
returnPath.GetFileName(name);
}
#endregion
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。