在看dnn时发现了一个很酷的功能:能通过ie浏览器实现对zip文件的压缩和生成zip文件文件压缩包的功能。在仔细看过程序以后发现它是调用的sharpziplib.dll类库中的内容实现的压缩与解压功能。上网查了一下sharpziplib,发现它居然是开源的,在http://www.icsharpcode.net网站上有下。在网站里关于sharpziplib的源文件和调用演示包括帮助文档都有下,不过当然全是e文的。(真不知在中国有哪家公司在做.net的开源,真的十分想看国产的优秀开源项目)
在sharpziplib中实现解压的方法(演示代码):
using system;
using system.text;
using system.collections;
using system.io;
using system.diagnostics;
using system.runtime.serialization.formatters.binary;
using system.data;
using icsharpcode.sharpziplib.bzip2;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.zip.compression;
using icsharpcode.sharpziplib.zip.compression.streams;
using icsharpcode.sharpziplib.gzip;

class mainclass
{
// 在控制命令行下输入要解压的zip文件名
public static void main(string[] args)
{
// 创建读取zip文件对象
zipinputstream s = new zipinputstream(file.openread(args[0]));
// zip文件中的每一个文件
zipentry theentry;
// 循环读取zip文件中的每一个文件
while ((theentry = s.getnextentry()) != null) {
console.writeline(theentry.name);
string directoryname = path.getdirectoryname(theentry.name);
string filename = path.getfilename(theentry.name);
// create directory
directory.createdirectory(directoryname);
if (filename != string.empty) {
// 解压文件
filestream streamwriter = file.create(theentry.name);
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();
}
}
在sharpziplib中实现压缩的方法:
using system;
using system.io;
using icsharpcode.sharpziplib.checksums;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.gzip;
class mainclass
{
// 输入要压缩的文件夹和要创建的zip文件文件名称
public static void main(string[] args)
{
string[] filenames = directory.getfiles(args[0]);
crc32 crc = new crc32();
// 创建输出zip文件对象
zipoutputstream s = new zipoutputstream(file.create(args[1]));
// 设置压缩等级
s.setlevel(6); // 0 – store only to 9 – means best compression
// 循环读取要压缩的文件,写入压缩包
foreach (string file in filenames) {
filestream fs = file.openread(file);
byte[] buffer = new byte[fs.length];
fs.read(buffer, 0, buffer.length);
zipentry entry = new zipentry(file);
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);
}
s.finish();
s.close();
}
}类中应该还有其他功能,还没有来得及看。具体sharpziplib中是如何实行的也还没有来得及看,先试一试最简单功能,大家有兴趣可以下载看看。默认提供的演示程序是控制台下运行的(好像还有其他环境中运行的,不过我没有试),我照着做了一个web应用程序的,希望能对大家有用。


