您的位置:首页 > 编程语言 > C#

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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: