使用的类库为:ICSharpCode.SharpZipLib.dll

一种是打包整个文件夹,另一种是打包指定的多个文件,大同小异:

 using ICSharpCode.SharpZipLib.Zip;

 public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 打包下载某文件夹里的所有文件 //需要打包的文件夹
string path = "UploadImage/Images/";
string serverPath = Server.MapPath(path); //创建临时文件夹
string tempName = DateTime.Now.ToString("yyyyMMddHHMMss");
string tempFolder = Path.Combine(serverPath, tempName);
Directory.CreateDirectory(tempFolder); //遍历文件夹中所有的文件到临时文件夹中
DirectoryInfo folder = new DirectoryInfo(serverPath);
foreach (FileInfo file in folder.GetFiles())
{
string filename = file.Name;
File.Copy(serverPath + "/" + filename, tempFolder + "/" + filename);
} //压缩文件
compressFiles(tempFolder, tempFolder + "\\\\" + tempName + ".rar");
//下载文件
// DownloadRAR(tempFolder + "\\\\" + tempName + ".rar", "这里下载文件重命名后的名称"); //某些文件打包下载
DownLodeSum(); } /// <summary>
/// 某些文件打包下载
/// </summary>
public void DownLodeSum()
{
//临时文件夹所在目录
string path = "UploadImage/";
string serverPath = Server.MapPath(path); //创建临时文件夹
string tempName = DateTime.Now.ToString("yyyyMMddHHMMss");
string tempFolder = Path.Combine(serverPath, tempName);
Directory.CreateDirectory(tempFolder); //复制需要压缩的文件到临时文件夹中
File.Copy(Server.MapPath("UploadImage/Images/bg-b.png"), Server.MapPath(path + tempName + "/bg-b.png"));
File.Copy(Server.MapPath("UploadImage/Images/bg-j.png"), Server.MapPath(path + tempName + "/bg-j.png"));
File.Copy(Server.MapPath("UploadImage/Images/icon-cart.png"), Server.MapPath(path + tempName + "/icon-cart.png")); //压缩文件
compressFiles(tempFolder, tempFolder + "\\\\" + tempName + ".rar");
//下载文件
DownloadRAR(tempFolder + "\\\\" + tempName + ".rar", "这里下载文件重命名后的名称"); } /// <summary>
/// 压缩文件
/// </summary>
/// <param name="dir">文件目录</param>
/// <param name="zipfilename">zip文件名</param>
public static void compressFiles(string dir, string zipfilename)
{
if (!Directory.Exists(dir))
{
return;
}
try
{
string[] filenames = Directory.GetFiles(dir);
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipfilename)))
{ s.SetLevel(); // 0 - store only to 9 - means best compression byte[] buffer = new byte[]; foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
s.Finish();
s.Close();
}
}
catch
{ }
} /// <summary>
/// 下载生成的RAR文件
/// </summary>
private void DownloadRAR(string file, string name)
{
FileInfo fileInfo = new FileInfo(file);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + name + ".rar");
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
string tempPath = file.Substring(, file.LastIndexOf("\\\\"));
//删除临时目录下的所有文件
DeleteFiles(tempPath);
//删除空目录
Directory.Delete(tempPath);
Response.End();
} /// <summary>
/// 删除临时目录下的所有文件
/// </summary>
/// <param name="tempPath">临时目录路径</param>
private void DeleteFiles(string tempPath)
{
DirectoryInfo directory = new DirectoryInfo(tempPath);
try
{
foreach (FileInfo file in directory.GetFiles())
{
if (file.Attributes.ToString().IndexOf("ReadOnly") != -)
{
file.Attributes = FileAttributes.Normal;
}
File.Delete(file.FullName);
}
}
catch (Exception)
{
throw;
}
}
}

点击下载源码

ASP.NET 打包下载文件的更多相关文章

  1. asp.net mvc5 下载文件方法

    控制器自带的 FileContentResult 可以让我们很方便的返回文件到服务端,减少了很多步骤.用于下载文件的时候,像视频.文本.图片这种浏览器支持的文件,默认就会被浏览器打开.这时候想让它变成 ...

  2. ASP.NET批量下载文件的方法

    一.实现步骤 在用户操作界面,由用户选择需要下载的文件,系统根据所选文件,在服务器上创建用于存储所选文件的临时文件夹,将所选文件拷贝至临时文件夹.然后调用 RAR程序,对临时文件夹进行压缩,然后输出到 ...

  3. ASP.NET批量下载文件

    一.实现步骤 在用户操作界面,由用户选择需要下载的文件,系统根据所选文件,在服务器上创建用于存储所选文件的临时文件夹,将所选文件拷贝至临时文件夹.然后调用 RAR程序,对临时文件夹进行压缩,然后输出到 ...

  4. Asp.net mvc 下载文件

    前言 最近有需求需要下载文件,可能是image的图片,也可能是pdf报告,也可能是微软的word或者excel文件. 这里就整理了asp.net mvc 和asp.net webapi 下载的方法 A ...

  5. php打包下载文件

    使用前请先开启:查看下php.ini里面的extension=php_zip.dll前面的分号有没有去掉; $zip=new \ZipArchive(); $zifile = 'download/' ...

  6. C# ASP 上传/下载文件

    1.  上传文件前台页面 <div style="padding-left:20px;"> <asp:FileUpload ID="FileUpload ...

  7. Asp.Net 之 下载文件的常用方式

    1.直接使用Response.TransmitFile(filename)方法 protected void Button_Click(object sender, EventArgs e) { /* ...

  8. ASP.NET 后台下载文件方法

    void DownLoadFile(string fileName) { string filePath = Server.MapPath(fileName);//路径 //以字符流的形式下载文件 F ...

  9. asp.net core 下载文件,上传excel文件

    下载文件: 代码: 后端代码: public IActionResult DownloadFile() { var FilePath = @"./files/deparment.xlsx&q ...

随机推荐

  1. prototype.js 源码解读(01)

    prototype.js是一个设计的非常优雅且很有实用价值的js基础类库,其源码非常值得研究.研究它的源码不仅能提升个人水平,而且对你打下坚实的js基础也很有帮助.因本人技术水平有限,该解读仅供参考. ...

  2. 关于Android4.2后WebView的js方法需要加@JavascriptInterface

    解读: targetSdkVersion>=17时,需要加上@JavascriptInterface,否则报错Uncaught TypeError: Object [object Object] ...

  3. wcf纯代码创建控制台应用

    https://svn.apache.org/repos/asf/incubator/stonehenge/contrib/stocktrader/dotnet/ stocktrader项目的dotn ...

  4. BZOJ1666: [Usaco2006 Oct]Another Cow Number Game 奶牛的数字游戏

    1666: [Usaco2006 Oct]Another Cow Number Game 奶牛的数字游戏 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 5 ...

  5. Light OJ 1031 - Easy Game(区间DP)

    题目大意: 给你一个n,代表n个数字,现在有两个选手,选手A,B轮流有有一次机会,每个选手一次可以得到一个或者多个数字,从左侧或者右侧,但是不能同时从两边取数字,当所有的数字被取完,那么游戏结束.然后 ...

  6. winphone 开发学习笔记(2)

    导航 NavigationService.Navigate(new Uri("xxxx.xaml",UriKind.Relative)) xxx表示要跳转的目标页面 页面和页面导航 ...

  7. DBI接口和DPI接口的区别

    1)DBI接口 A,也就是通常所讲的MCU借口,俗称80 system接口.The lcd interface between host processor and LCM device list a ...

  8. Google的一些功能和软件

    本博文的主要内容有 .Google的一些功能和软件 Google的一些功能和软件 1.  iGoogle 2.  Google Earth 3.  Google Talk http://www.goo ...

  9. poj 2752 Seek the Name, Seek the Fame【KMP算法分析记录】【求前后缀相同的子串的长度】

    Seek the Name, Seek the Fame Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 14106   Ac ...

  10. C# 操作配置文件

    1.配置文件app.config的书写: string mdbPath = ConfigurationManager.AppSettings["mdbPath"].ToString ...