网站上的文件是临时文件, 浏览器下载完成, 网站需要将其删除.

下面的写法, 文件读写后没关闭, 经常删除失败.

/// <summary>
/// 下载服务器文件,参数一物理文件路径(含文件名称及后缀),参数二文件名称
/// </summary>
/// <param name="PhysicalPath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool DownLoad(string PhysicalPath, string fileName)
{
bool _bool = false;
string[] arrSplit = PhysicalPath.Split('.'); string fileType = arrSplit[arrSplit.Length - ];//获得下载文件的类型
try
{
if ("xls".Equals(fileType))
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
}
//else if("xml".Equals(fileType))
//{
// HttpContext.Current.Response.ContentType = "application/octet-stream";
//}
else
{
HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
} HttpContext.Current.Response.Charset = GlobalVar.ADMIN_CHARSET_ENCODING;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(fileName));//设置文件名称
HttpContext.Current.Response.TransmitFile(PhysicalPath);
_bool = true;
}
catch
{ _bool = false;
}
finally
{
//发送到客户端的文件流,如果点击取消,此临时文件会一直打开着,无法快速删除,影响不大,之后再行解决
// HttpContext.Current.Response.Clear();
// HttpContext.Current.Response.Close();
} return _bool;
}

下面是正确写法, 解决用户点击取消, 临时文件还打开着的问题(down临时文件夹可不要)

/// <summary>
/// 下载服务器文件,参数一物理文件路径(含文件名称及后缀),参数二文件名称
/// </summary>
/// <param name="PhysicalPath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static void DownLoad(string PhysicalPath, string NewFileName)
{
//清空下down目录下大于1小时的文件
string[] files = Directory.GetFiles(Utils.GetMapPath("down"));
foreach (string str in files)
{
FileInfo fileInfo = new FileInfo(str);
if (Math.Abs((fileInfo.CreationTime - DateTime.Now).TotalHours) > )
{
try
{
File.Delete(str);
}
catch
{
Func.SaveLog(, "删除" + str + "文件失败");
}
}
} //将要下载的文件复制到down临时文件夹
string strDownFileName = Path.Combine(Utils.GetMapPath("down"), new Random().Next(int.MaxValue).ToString());
File.Copy(PhysicalPath, strDownFileName, true); System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[]; // Length of the file:
int length; // Total bytes to read:
long dataToRead; // Identify the file to download including its path.
string filepath = strDownFileName; // Identify the file name.
//string filename = System.IO.Path.GetFileName(filepath); try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read:
dataToRead = iStream.Length; HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Utils.UrlEncode(NewFileName)); // Read the bytes.
while (dataToRead > )
{
// Verify that the client is connected.
if (HttpContext.Current.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, , ); // Write the data to the current output stream.
HttpContext.Current.Response.OutputStream.Write(buffer, , length); // Flush the data to the HTML output.
HttpContext.Current.Response.Flush(); buffer = new Byte[];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
HttpContext.Current.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}

Asp.net下载文件的更多相关文章

  1. Asp.Net 下载文件的几种方式

    asp.net下载文件几种方式 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法 ...

  2. asp.net下载文件几种方式

    测试时我以字符流的形式下载文件,可行,前几个仅作参考 protected void Button1_Click(object sender, EventArgs e)  {  /*  微软为Respo ...

  3. asp.net 下载文件(图片、word、excel等)

    string filePath = Server.MapPath("~/excel.xlsx"); if (File.Exists(filePath)) { FileStream ...

  4. ASP.NET 下载文件方式

    protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法TransmitFile来解决使 ...

  5. asp.net 下载文件几种方式

    protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法TransmitFile来解决使 ...

  6. ASP.NET 下载文件并继续执行JS解决方法

    需求说明:当用户点击按钮时使当前按钮为不可用,并打开新页面,关闭新页面时,按钮变为可用.并且如果不关闭新页面,当前按钮过10秒钟自动变为可用. 包含3个页面: 一.按钮页 前台代码:当刷新后采用js进 ...

  7. asp.net下载文件方法

    /// <summary> /// 下载 /// </summary> /// <param name="url"></param> ...

  8. asp.net下载文件的几种方法

    最近做东西遇到了下载相关的问题.在这里总结一下自己处理的方法. 1.以字节流的形式向页面输出数据以下载Excel为例子. string path=Server.MapPath("文件路径&q ...

  9. 解决用ASP.NET下载文件时,文件名为乱码的问题

    关键就一句:                    string strTemp = System.Web.HttpUtility.UrlEncode(strName, System.Text.Enc ...

随机推荐

  1. MySQL数据库表中有usage字段名后的后果

    一个很奇怪的42000的错误,折腾了我一晚上.... 我的系统是Spring + SpringMVC + MyBatis结构, 数据库的mapper以及model等文件都是用MyBatisGenera ...

  2. Hibernate3回顾-1-部署

    web备份版本,详见doc版本. 一.背景(部署简单回顾) 我们知道,一个Hibernate快速上手的简单流程是这样. 1引入对应jar包. 中间涉及log4的jar包和配置,略. 2 实体类 pac ...

  3. LintCode "Coins in a Line II" !

    Nice one to learn: DP + Game Theoryhttps://lefttree.gitbooks.io/leetcode/content/dynamicProgramming2 ...

  4. SPOJ #453. Sums in a Triangle (tutorial)

    It is a small fun problem to solve. Since only a max sum is required (no need to print path), we can ...

  5. SSH_框架整合2—查询显示

    4. 完成功能. (1)com.atguigu.ssh.actions包下新建EmployeeAction.java package com.atguigu.ssh.actions; import j ...

  6. 读书笔记:应用随机过程:概率模型导论:Aloha协议问题

    例4.16,Aloha协议:就本书例题所涉及的部分来说,几乎等同于CSMA.这个例题重写如下: 考察一个包含多个设备的通信系统,其中在每个时间段发送信息的设备个数是独立同分布的.......每个设备将 ...

  7. oracle行转列(连接字符串函数)

    方法一:wmsys.wm_concat(column) 介绍:其函数在Oracle 10g推出,在10g版本中,返回字符串类型,在11g版本中返回clob类型.括号里面的参数是列,而且可以是多个列的集 ...

  8. JavaScript中文字符验证的函数/正则

    /** * 中文字符验证 * @param {} str * @return {Boolean} */ function checkChinese(str) { var re = /[^\u4e00- ...

  9. 在Visual Studio 2010/2012中 找不到创建WebService的项目模板

    参考文章: http://blog.sina.com.cn/s/blog_6d545999010152wb.html 在 Visual Studio 2010 或者2012的新建 Web 应用程序或者 ...

  10. XML封装与验证消息

    Document document = DocumentHelper.createDocument(); document.setXMLEncoding(ChARSET_UTF_8); Element ...