C# 下载文件
2016-06-29 14:56
441 查看
1.0下载文件
public void DownLoadeFile(string filePath, string name) { try { filePath = Server.MapPath(filePath); if (System.IO.File.Exists(filePath)) { FileInfo info = new FileInfo(filePath); long fileSize = info.Length; Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachement;filename=" + name); //指定文件大小 Response.AddHeader("Content-Length", fileSize.ToString()); Response.WriteFile(filePath, 0, fileSize); Response.Flush(); } } catch { } finally { Response.Close(); } }
2.0 打压缩包下载
/// <summary> /// 文件打包下载 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnDownLoad_Click(object sender, EventArgs e) { DataTable dt = SelectA132(domainOrderId); List<string> filesPathList = new List<string>(); if (dt != null && dt.Rows.Count > 0) { if (dt.Rows[0]["EnterpriseState"].ToString() == "1")//企业状态1代表单位0代表个人 { filesPathList.Add(dt.Rows[0]["EnterpriseImgURL"].ToString()); } filesPathList.Add(dt.Rows[0]["PersonalImgURL"].ToString()); if (filesPathList != null && filesPathList.Count > 0) { zip zip = new zip(); zip.DwonloadZip(filesPathList, dt.Rows[0]["domain"].ToString() + ".zip"); } } }
/// <summary> /// 压缩文件类 /// </summary> public class zip { /// <summary> /// 所有文件缓存 /// </summary> List<string> filesPathList = new List<string>(); /// <summary> /// 所有空目录缓存 /// </summary> List<string> emptyPathList = new List<string>(); /// <summary> /// 多文件打包下载 /// </summary> /// <param name="filesPathList"></param> /// <param name="zipName"></param> public void DwonloadZip(List<string> filesPathList, string zipName) { MemoryStream ms = new MemoryStream();//存储区内存流 byte[] buffer = null; var context = HttpContext.Current; using (ZipFile zfile = ZipFile.Create(ms)) { zfile.BeginUpdate(); /*通过这个名称格式化器,可以将里面的文件名进行一些处理。 默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。*/ zfile.NameTransform = new MyNameTransform(); foreach (var it in filesPathList) { if (!string.IsNullOrEmpty(it)) { zfile.Add(it); } } zfile.CommitUpdate(); buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, buffer.Length); } context.Response.AddHeader("content-disposition", "attachment;filename=" + zipName); context.Response.BinaryWrite(buffer); context.Response.Flush(); context.Response.End(); } }
相关文章推荐
- C# Index 定义索---引具体使用2
- C#实现单链表(线性表)完整实例
- 用C#获取局域网内所有机器
- C# Index 定义索---引具体使用
- C# Index 定义索---引具体使用
- C#在高性能计算领域为什么性能却如此不尽人意
- C#实现顺序表(线性表)完整实例
- C#遍历集合与移除元素的方法
- c#大圣之路笔记——c# DataGrid checkbox 操作
- C#中的BackgroundWorker控件
- C#中的线程(四)高级话题
- C#中的线程(三)多线程
- C#中的线程(一)入门
- C#中的线程(二)线程同步
- C#中哈希表(HashTable)用法实例详解(添加/移除/判断/遍历/排序等)
- C#使用foreach循环遍历数组完整实例
- c#传入域名返回对应的IP
- c#获取WebBrowser中的userAgent
- c#geckofx文件流下载
- C#遍历文件夹及其子目录的完整实现方法