asp.net C#实现解压缩文件的方法
本文实例讲述了asp.netC#实现解压缩文件的方法。一共给大家介绍了三段代码,一个是简单的解压缩单个zip文件,后一个可以解压批量的大量的但需要调用ICSharpCode.SharpZipLib.dll类了,最后一个比较实例可压缩也可以解压缩了分享给大家供大家参考。具体如下:
解压缩单个文件:
usingSystem.IO;
usingSystem.IO.Compression;
stringsourceFile=@"D:2.zip";
stringdestinationFile=@"D:1.txt";
privateconstlongBUFFER_SIZE=20480;
//makesurethesourcefileisthere
if(File.Exists(sourceFile))
{
FileStreamsourceStream=null;
FileStreamdestinationStream=null;
GZipStreamdecompressedStream=null;
byte[]quartetBuffer=null;
try
{
//Readinthecompressedsourcestream
sourceStream=newFileStream(sourceFile,FileMode.Open);
//Createacompressionstreampointingtothedestiantionstream
decompressedStream=newDeflateStream(sourceStream,CompressionMode.Decompress,true);
//Readthefootertodeterminethelengthofthedestiantionfile
quartetBuffer=newbyte[4];
intposition=(int)sourceStream.Length-4;
sourceStream.Position=position;
sourceStream.Read(quartetBuffer,0,4);
sourceStream.Position=0;
intcheckLength=BitConverter.ToInt32(quartetBuffer,0);
byte[]buffer=newbyte[checkLength+100];
intoffset=0;
inttotal=0;
//Readthecompresseddataintothebuffer
while(true)
{
intbytesRead=decompressedStream.Read(buffer,offset,100);
if(bytesRead==0)
break;
offset+=bytesRead;
total+=bytesRead;
}
//Nowwriteeverythingtothedestinationfile
destinationStream=newFileStream(destinationFile,FileMode.Create);
destinationStream.Write(buffer,0,total);
//andflusheveryhtingtocleanoutthebuffer
destinationStream.Flush();
}
catch(ApplicationExceptionex)
{
Console.WriteLine(ex.Message,"解压文件时发生错误:");
}
finally
{
//Makesureweallwayscloseallstreams
if(sourceStream!=null)
sourceStream.Close();
if(decompressedStream!=null)
decompressedStream.Close();
if(destinationStream!=null)
destinationStream.Close();
}
}
批量解压缩(这需要调用一个解压缩类库。。ICSharpCode.SharpZipLib.dll)
usingSystem;
usingSystem.IO;
usingSystem.Collections.Generic;
usingSystem.Text;
usingICSharpCode.SharpZipLib.Zip;
namespaceZipLib
{
///<summary>
///解压缩类
///</summary>
publicstaticclassZIP
{
///<summary>
///解压ZIP文件包
///</summary>
///<paramname="strZipFile">ZIP文件路径</param>
///<paramname="strDir">解压后的文件目录路径</param>
///<returns>是否解压成功</returns>
publicstaticboolunzipFiles(stringstrZipFile,stringstrDir)
{
//判断ZIP文件是否存在
if(File.Exists(strZipFile))
{
//判断目录是否存在
boolbUnzipDir=false;
//判断是否需要创建目录
if(!Directory.Exists(strDir))
bUnzipDir=(Directory.CreateDirectory(strDir)!=null);
else
bUnzipDir=true;
//如果解压目录存在
if(bUnzipDir)
{
//获得ZIP数据流
ZipInputStreamzipStream=newZipInputStream(File.OpenRead(strZipFile));
if(zipStream!=null)
{
ZipEntryzipEntry=null;
while((zipEntry=zipStream.GetNextEntry())!=null)
{
stringstrUnzipFile=strDir+"//"+zipEntry.Name;
stringstrFileName=Path.GetFileName(strUnzipFile);
stringstrDirName=Path.GetDirectoryName(strUnzipFile);
//是否为解压目录
if(!string.IsNullOrEmpty(strDirName))
Directory.CreateDirectory(strDirName);
//是否为解压文件
if(!string.IsNullOrEmpty(strFileName))
{
//解压文件
FileStreamunzipFileStream=newFileStream(strUnzipFile,FileMode.Create);
if(unzipFileStream!=null)
{
byte[]buf=newbyte[2048];
intsize=0;
while((size=zipStream.Read(buf,0,2048))>0)
unzipFileStream.Write(buf,0,size);
//关闭Stream
unzipFileStream.Flush();
unzipFileStream.Close();
}
}
}
//关闭ZIP流
zipStream.Close();
//返回值
returntrue;
}
}
}
returnfalse;
}
}
}上面两个都是解压缩文件,下面我们把压缩与解压缩放在一个实例中。
最近要做一个项目涉及到C#中压缩与解压缩的问题的解决方法,大家分享。
这里主要解决文件夹包含文件夹的解压缩问题。
下载SharpZipLib.dll,在http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx中有最新免费版本,“Assembliesfor.NET1.1,.NET2.0,.NETCF1.0,.NETCF2.0:Download[297KB]”点击Download可以下载,解压后里边有好多文件夹,因为不同的版本,我用的FW2.0。
或者点击此处本站下载。
引用SharpZipLib.dll,在项目中点击项目右键-->添加引用-->浏览,找到要添加的DLL-->确认
改写了文件压缩和解压缩的两个类,新建两个类名字为ZipFloClass.cs,UnZipFloClass.cs
源码如下
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.IO;
usingICSharpCode.SharpZipLib.Checksums;
usingICSharpCode.SharpZipLib.Zip;
usingICSharpCode.SharpZipLib.GZip;
///<summary>
///ZipFloClass的摘要说明
///</summary>
publicclassZipFloClass
{
publicvoidZipFile(stringstrFile,stringstrZip)
{
if(strFile[strFile.Length-1]!=Path.DirectorySeparatorChar)
strFile+=Path.DirectorySeparatorChar;
ZipOutputStreams=newZipOutputStream(File.Create(strZip));
s.SetLevel(6);//0-storeonlyto9-meansbestcompression
zip(strFile,s,strFile);
s.Finish();
s.Close();
}
privatevoidzip(stringstrFile,ZipOutputStreams,stringstaticFile) { if(strFile[strFile.Length-1]!=Path.DirectorySeparatorChar)strFile+=Path.DirectorySeparatorChar; Crc32crc=newCrc32(); string[]filenames=Directory.GetFileSystemEntries(strFile); foreach(stringfileinfilenames) { if(Directory.Exists(file)) { zip(file,s,staticFile); } else//否则直接压缩文件 { //打开压缩文件 FileStreamfs=File.OpenRead(file); byte[]buffer=newbyte[fs.Length]; fs.Read(buffer,0,buffer.Length); stringtempfile=file.Substring(staticFile.LastIndexOf("\")+1); ZipEntryentry=newZipEntry(tempfile); entry.DateTime=DateTime.Now; entry.Size=fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc=crc.Value; s.PutNextEntry(entry); s.Write(buffer,0,buffer.Length); } } } }