asp.net C#实现解压缩文件的方法
本文实例讲述了asp.net c#实现解压缩文件的方法。一共给大家介绍了三段代码,一个是简单的解压缩单个zip文件,后一个可以解压批量的大量的但需要调用icsharpcode.sharpziplib.dll类了,最后一个比较实例可压缩也可以解压缩了分享给大家供大家参考。具体如下:
解压缩单个文件:
using system.io.compression;
string sourcefile=@"d:2.zip";
string destinationfile=@"d:1.txt";
private const long buffer_size = 20480;
// make sure the source file is there
if (file.exists ( sourcefile ))
{
filestream sourcestream = null;
filestream destinationstream = null;
gzipstream decompressedstream = null;
byte[] quartetbuffer = null;
try
{
// read in the compressed source stream
sourcestream = new filestream ( sourcefile, filemode.open );
// create a compression stream pointing to the destiantion stream
decompressedstream = new deflatestream ( sourcestream, compressionmode.decompress, true );
// read the footer to determine the length of the destiantion file
quartetbuffer = new byte[4];
int position = (int)sourcestream.length - 4;
sourcestream.position = position;
sourcestream.read ( quartetbuffer, 0, 4 );
sourcestream.position = 0;
int checklength = bitconverter.toint32 ( quartetbuffer, 0 );
byte[] buffer = new byte[checklength + 100];
int offset = 0;
int total = 0;
// read the compressed data into the buffer
while ( true )
{
int bytesread = decompressedstream.read ( buffer, offset, 100 );
if ( bytesread == 0 )
break;
offset += bytesread;
total += bytesread;
}
// now write everything to the destination file
destinationstream = new filestream ( destinationfile, filemode.create );
destinationstream.write ( buffer, 0, total );
// and flush everyhting to clean out the buffer
destinationstream.flush ( );
}
catch ( applicationexception ex )
{
console.writeline(ex.message, "解压文件时发生错误:");
}
finally
{
// make sure we allways close all streams
if ( sourcestream != null )
sourcestream.close ( );
if ( decompressedstream != null )
decompressedstream.close ( );
if ( destinationstream != null )
destinationstream.close ( );
}
}
批量解压缩(这需要调用一个解压缩类库。。 icsharpcode.sharpziplib.dll)
using system.io;
using system.collections.generic;
using system.text;
using icsharpcode.sharpziplib.zip;
namespace ziplib
{
/// <summary>
/// 解压缩类
/// </summary>
public static class zip
{
/// <summary>
/// 解压zip文件包
/// </summary>
/// <param name="strzipfile">zip文件路径</param>
/// <param name="strdir">解压后的文件目录路径</param>
/// <returns>是否解压成功</returns>
public static bool unzipfiles(string strzipfile, string strdir)
{
//判断zip文件是否存在
if (file.exists(strzipfile))
{
//判断目录是否存在
bool bunzipdir = false;
//判断是否需要创建目录
if (!directory.exists(strdir))
bunzipdir = (directory.createdirectory(strdir) != null);
else
bunzipdir = true;
//如果解压目录存在
if (bunzipdir)
{
//获得zip数据流
zipinputstream zipstream = new zipinputstream(file.openread(strzipfile));
if (zipstream != null)
{
zipentry zipentry = null;
while ((zipentry = zipstream.getnextentry()) != null)
{
string strunzipfile = strdir + "//" + zipentry.name;
string strfilename = path.getfilename(strunzipfile);
string strdirname = path.getdirectoryname(strunzipfile);
//是否为解压目录
if (!string.isnullorempty(strdirname))
directory.createdirectory(strdirname);
//是否为解压文件
if (!string.isnullorempty(strfilename))
{
//解压文件
filestream unzipfilestream = new filestream(strunzipfile, filemode.create);
if (unzipfilestream != null)
{
byte[] buf = new byte[2048];
int size = 0;
while ((size = zipstream.read(buf, 0, 2048)) > 0)
unzipfilestream.write(buf, 0, size);
//关闭stream
unzipfilestream.flush();
unzipfilestream.close();
}
}
}
//关闭zip流
zipstream.close();
//返回值
return true;
}
}
}
return false;
}
}
}
上面两个都是解压缩文件,下面我们把压缩与解压缩放在一个实例中。
最近要做一个项目涉及到c#中压缩与解压缩的问题的解决方法,大家分享。
这里主要解决文件夹包含文件夹的解压缩问题。
下载sharpziplib.dll,在http://www.icsharpcode.net/opensource/sharpziplib/download.aspx中有最新免费版本,“assemblies for .net 1.1, .net 2.0, .net cf 1.0, .net cf 2.0: download [297 kb] ”点击download可以下载,解压后里边有好多文件夹,因为不同的版本,我用的fw2.0。
或者点击此处本站下载。
引用sharpziplib.dll,在项目中点击项目右键-->添加引用-->浏览,找到要添加的dll-->确认
改写了文件压缩和解压缩的两个类,新建两个类名字为zipfloclass.cs,unzipfloclass.cs
源码如下
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.io;
using icsharpcode.sharpziplib.checksums;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.gzip;
/// <summary>
/// zipfloclass 的摘要说明
/// </summary>
public class zipfloclass
{
public void zipfile(string strfile, string strzip)
{
if (strfile[strfile.length - 1] != path.directoryseparatorchar)
strfile += path.directoryseparatorchar;
zipoutputstream s = new zipoutputstream(file.create(strzip));
s.setlevel(6); // 0 - store only to 9 - means best compression
zip(strfile, s, strfile);
s.finish();
s.close();
}
private void zip(string strfile, zipoutputstream s, string staticfile)
{
if (strfile[strfile.length - 1] != path.directoryseparatorchar) strfile += path.directoryseparatorchar;
crc32 crc = new crc32();
string[] filenames = directory.getfilesystementries(strfile);
foreach (string file in filenames)
{
if (directory.exists(file))
{
zip(file, s, staticfile);
}
else // 否则直接压缩文件
{
//打开压缩文件
filestream fs = file.openread(file);
byte[] buffer = new byte[fs.length];
fs.read(buffer, 0, buffer.length);
string tempfile = file.substring(staticfile.lastindexof("\") + 1);
zipentry entry = new zipentry(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);
}
}
}
}
using system.data;
using system.web;
using system.text;
using system.collections;
using system.io;
using system.diagnostics;
using system.runtime.serialization.formatters.binary;
using icsharpcode.sharpziplib.bzip2;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.zip.compression;
using icsharpcode.sharpziplib.zip.compression.streams;
using icsharpcode.sharpziplib.gzip;
using icsharpcode.sharpziplib.checksums;
/// <summary>
/// unzipfloclass 的摘要说明
/// </summary>
public class unzipfloclass
{
public string unzipfile(string targetfile, string filedir)
{
string rootfile = " ";
try
{
//读取压缩文件(zip文件),准备解压缩
zipinputstream s = new zipinputstream(file.openread(targetfile.trim()));
zipentry theentry;
string path = filedir;
//解压出来的文件保存的路径
string rootdir = " ";
//根目录下的第一个子文件夹的名称
while ((theentry = s.getnextentry()) != null)
{
rootdir = path.getdirectoryname(theentry.name);
//得到根目录下的第一级子文件夹的名称
if (rootdir.indexof("\") >= 0)
{
rootdir = rootdir.substring(0, rootdir.indexof("\") + 1);
}
string dir = path.getdirectoryname(theentry.name);
//根目录下的第一级子文件夹的下的文件夹的名称
string filename = path.getfilename(theentry.name);
//根目录下的文件名称
if (dir != " " )
//创建根目录下的子文件夹,不限制级别
{
if (!directory.exists(filedir + "\" + dir))
{
path = filedir + "\" + dir;
//在指定的路径创建文件夹
directory.createdirectory(path);
}
}
else if (dir == " " && filename != "")
//根目录下的文件
{
path = filedir;
rootfile = filename;
}
else if (dir != " " && filename != "")
//根目录下的第一级子文件夹下的文件
{
if (dir.indexof("\") > 0)
//指定文件保存的路径
{
path = filedir + "\" + dir;
}
}
if (dir == rootdir)
//判断是不是需要保存在根目录下的文件
{
path = filedir + "\" + rootdir;
}
//以下为解压缩zip文件的基本步骤
//基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
if (filename != string.empty)
{
filestream streamwriter = file.create(path + "\" + filename);
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 rootfile;
}
catch (exception ex)
{
return "1; " + ex.message;
}
}
}
引用,新建一个页面,添加两个按钮,为按钮添加click事件
源码如下
{
string[] fileproperties = new string[2];
fileproperties[0] = "d:\unzipped\";//待压缩文件目录
fileproperties[1] = "d:\zip\a.zip"; //压缩后的目标文件
zipfloclass zc = new zipfloclass();
zc.zipfile(fileproperties[0], fileproperties[1]);
}
protected void button2_click(object sender, eventargs e)
{
string[] fileproperties = new string[2];
fileproperties[0] = "d:\zip\b.zip";//待解压的文件
fileproperties[1] = "d:\unzipped\";//解压后放置的目标目录
unzipfloclass unzc = new unzipfloclass();
unzc.unzipfile(fileproperties[0], fileproperties[1]);
}
希望本文所述对大家的asp.net程序设计有所帮助。
上一篇: MySQL中使用自定义变量 编写偷懒的UNION示例
下一篇: c# xml API操作的小例子