using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.web;
using icsharpcode.sharpziplib.zip;
namespace gzrmis.main.business
{
public class ziphelper
{
///
/// 存放待压缩的文件的绝对路径
///
private list absolutepaths { set; get; }
public string errormsg { set; get; }
public ziphelper()
{
errormsg = ;
absolutepaths = new list();
}
///
/// 添加压缩文件或文件夹
///
/// 文件或文件夹的绝对路径
public void addfile(string _fileabsolutepath)
{
absolutepaths.add(_fileabsolutepath);
}
///
/// 压缩文件或者文件夹
///
/// 压缩后文件的存放路径 如c:\\windows\abc.zip
/// 压缩级别0~9,数字越大压缩率越高,默认为5
///
public bool compressionzip(string _depositpath,int _level=5)
{
bool result = true;
filestream fs = null;
try
{
zipoutputstream comstream = new zipoutputstream(file.create(_depositpath));
comstream.setlevel(_level); //压缩等级
foreach (string path in absolutepaths)
{
//如果是目录
if (directory.exists(path))
{
zipfloder(path, comstream, path);
}
else if (file.exists(path))//如果是文件
{
fs = file.openread(path);
byte[] bts = new byte[fs.length];
fs.read(bts, 0, bts.length);
zipentry ze = new zipentry(new fileinfo(path).name);
comstream.putnextentry(ze); //为压缩文件流提供一个容器
comstream.write(bts, 0, bts.length); //写入字节
}
}
comstream.finish(); // 结束压缩
comstream.close();
}
catch (exception ex)
{
if (fs != null)
{
fs.close();
}
errormsg = ex.message;
result = false;
}
return result;
}
//压缩文件夹
private void zipfloder(string _ofloderpath, zipoutputstream zos, string _floderpath)
{
foreach (filesysteminfo item in new directoryinfo(_floderpath).getfilesysteminfos())
{
if (directory.exists(item.fullname))
{
zipfloder(_ofloderpath, zos, item.fullname);
}
else if (file.exists(item.fullname))//如果是文件
{
directoryinfo odir = new directoryinfo(_ofloderpath);
string fullname2 = new fileinfo(item.fullname).fullname;
string path = odir.name + fullname2.substring(odir.fullname.length, fullname2.length - odir.fullname.length);//获取相对目录
filestream fs = file.openread(fullname2);
byte[] bts = new byte[fs.length];
fs.read(bts, 0, bts.length);
zipentry ze = new zipentry(path);
zos.putnextentry(ze); //为压缩文件流提供一个容器
zos.write(bts, 0, bts.length); //写入字节
}
}
}
///
/// 解压
///
/// 压缩文件路径
/// 解压的路径
///
public bool decompressionzip(string _depositpath, string _floderpath)
{
bool result = true;
filestream fs = null;
try
{
zipinputstream inpstream = new zipinputstream(file.openread(_depositpath));
zipentry ze = inpstream.getnextentry();//获取压缩文件中的每一个文件
directory.createdirectory(_floderpath);//创建解压文件夹
while (ze != null)//如果解压完ze则是null
{
if (ze.isfile)//压缩zipinputstream里面存的都是文件。带文件夹的文件名字是文件夹\\文件名
{
string[] strs = ze.name.split('\\');//如果文件名中包含’\\‘则表明有文件夹
if (strs.length > 1)
{
//两层循环用于一层一层创建文件夹
for (int i = 0; i < strs.length - 1; i++)
{
string floderpath = _floderpath;
for (int j = 0; j 0)
{
fs.write(bts, 0, i);
}
else
{
fs.flush();
fs.close();
break;
}
}
}
ze = inpstream.getnextentry();
}
}
catch (exception ex)
{
if (fs != null)
{
fs.close();
}
errormsg = ex.message;
result = false;
}
return result;
}
}
}