using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
namespace ZipFile
{
///
/// 压缩文件
///
public class ZipHelp
{
public string ZipName { get; set; }
///
/// 压缩文件夹
///
/// 需要压缩的文件夹路径(全路径)
/// 压缩后保存的路径且必须带后缀名如:D:aa.zip(如果为空字符则默认保存到同级文件夹名称为源文件名)
public void ZipFileMain(string zipSourcePath,string zipToFilePath)
{
string[] filenames = Directory.GetFiles(zipSourcePath);
ZipName = zipSourcePath.Substring(zipSourcePath.LastIndexOf("")+1);
//定义压缩更目录对象
Crc32 crc = new Crc32();
ZipOutputStream s = new ZipOutputStream(File.Create(zipToFilePath.Equals("")? zipSourcePath+".zip":zipToFilePath));
s.SetLevel(6); // 设置压缩级别
//递归压缩文件夹下的所有文件和字文件夹
AddDirToDir(crc, s,zipSourcePath);
s.Finish();
s.Close();
}
///
/// 压缩单个文件
///
/// 需要压缩的文件路径(全路径)
/// 压缩后保存的文件路径(如果是空字符则默认压缩到同目录下文件名为源文件名)
public void ZipByFile(string zipSourcePath,string zipToFilePath)
{
//定义压缩更目录对象
Crc32 crc = new Crc32();
string dirName = zipSourcePath.Substring(zipSourcePath.LastIndexOf("") + 1, zipSourcePath.LastIndexOf(".") - (zipSourcePath.LastIndexOf("") + 1)) + ".zip";
ZipOutputStream s = new ZipOutputStream(File.Create(zipToFilePath.Equals("")? zipSourcePath.Substring(0,zipSourcePath.LastIndexOf(""))+""+ dirName:zipToFilePath));
s.SetLevel(6); // 设置压缩级别
AddFileToDir(crc,s,zipSourcePath,0);
s.Finish();
s.Close();
}
///
/// 压缩单个文件到指定压缩文件夹下(内部调用)
///
///
///
/// 文件路径
public void AddFileToDir(Crc32 crc,ZipOutputStream s,string file,int dotype)
{
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string filename="";
if (dotype == 0)
filename = file.Substring(file.LastIndexOf("") + 1);
else
filename = file.Substring(file.IndexOf(ZipName));
ZipEntry entry = new ZipEntry(filename);
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);
}
///
/// 递归文件夹层级(内部调用)
///
///
///
///
public void AddDirToDir(Crc32 crc, ZipOutputStream s, string file)
{
//添加此文件夹下的文件
string[] files = Directory.GetFiles(file);
foreach (string i in files)
{
AddFileToDir(crc,s,i,1);
}
//查询此文件夹下的子文件夹
string[] dirs=Directory.GetDirectories(file);
foreach (string i in dirs)
{
AddDirToDir(crc,s,i);
}
}
}
}
|