首先下载ICSharpCode.SharpZipLib.dll,然后添加应用
接着建类 代码如下
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="args">源目录 压缩成的文件</param>
public void ZipFileMain(string[] args)
{
string[] filenames = Directory.GetFiles(args[0]);
Crc32 crc = new Crc32();
ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));
s.SetLevel(6); // 0 - store only to 9 - means best compression
yasuo(args[0], args[0], false, crc, s);
s.Finish();
s.Close();
}
/// <summary>
/// 循环压缩
/// </summary>
/// <param name="souce">源目录</param>
/// <param name="str">文件名或目录名</param>
/// <param name="isFile">是文件还是目录</param>
/// <param name="crc"></param>
/// <param name="s"></param>
public void yasuo(string souce, string str, bool isFile, Crc32 crc, ZipOutputStream s)
{
if (isFile)
{
try
{
//打开压缩文件
FileStream fs = File.OpenRead(str);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//FileInfo info = new FileInfo(file);
//压缩后显示的路径为当前压缩的目录;
ZipEntry entry = new ZipEntry(str.Replace(souce, ""));
//ZipEntry entry = new ZipEntry(file); //压缩后显示全路径
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
catch { }
}else{
//当前目录下的目录
foreach (string d in Directory.GetDirectories(str))
{
foreach (string file in Directory.GetFiles(d))
{
yasuo(souce, file, true, crc, s);
}
foreach (string dd in Directory.GetDirectories(d))
{
yasuo(souce, dd, false, crc, s);
}
}
//当前目录下的文件
foreach (string file in Directory.GetFiles(str))
{
yasuo(souce, file, true, crc, s);
}
}
}
具体调用如下
string[] FileProperties = new string[2];
FileProperties[0] = Server.MapPath("~/");//待压缩文件目录
FileProperties[1] = Server.MapPath("~/") + "\\备份.zip"; //压缩后的目标文件
clsZip Zc = new clsZip();
Zc.ZipFileMain(FileProperties);
Response.Write("<script language=javascript>alert('备份成功!')</script>");
参考文章 http://blog.csdn.net/qhq5152096/article/details/3863921