【转载博客园,代码未经楼主测试】
首先百度下载DLL:ICSharpCode.SharpZipLib.dll , 并且将DLL引用到项目中,如果本身存在此DLL 就不用再下载。
代码部分:
[C#] 纯文本查看 复制代码 using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.GZip;
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
DataTable dt1 = OleDbHelper.GetDataTable("select tupian from cp_img where cpid=" + ltl_id.Text + " and lx=0 order by px asc");
DataTable dt2 = OleDbHelper.GetDataTable("select tupian from cp_img where cpid=" + ltl_id.Text + " and lx=1 order by px asc");
if (dt1.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
byte[] buffer = null;
using (ZipFile file = ZipFile.Create(ms))
{
file.BeginUpdate();
file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
for (int i = 0; i < dt1.Rows.Count; i++)
{
file.Add(Server.MapPath(dt1.Rows[i]["tupian"].ToString()));
for (int j = 0; j < dt2.Rows.Count; j++)
{
file.Add(Server.MapPath(dt2.Rows[j]["tupian"].ToString()));
}
}
file.CommitUpdate();
buffer = new byte[ms.Length];
ms.Position = 0;
ms.Read(buffer, 0, buffer.Length);
}
string filename = ltl_mc.Text + "-" + DateTime.Now.ToString() + ".zip";
Response.AddHeader("content-disposition", "attachment;filename=" + filename + "");
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
}
}
public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
{
#region INameTransform 成员
public string TransformDirectory(string name)
{
return null;
}
public string TransformFile(string name)
{
return Path.GetFileName(name);
}
#endregion
}
|