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

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

/// <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. [Hibernate] - Study test project

    最近玩Hibernate的测试代码工程: http://files.cnblogs.com/HD/TestHibernate.7z

  2. 遇到 Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section的解决办法

    用记事本编辑*.EXE.config,在“<system.net>”节点加入<defaultProxy> <proxy usesystemdefault="Fa ...

  3. NodeJS的异步编程风格

    NodeJS的异步编程风格 http://www.infoq.com/cn/news/2011/09/nodejs-async-code NodeJS运行环境因其支持Javascript语言和异步编程 ...

  4. Sublime text2用户自定义配置

    [{ "keys": ["ctrl+d"], "command": "run_macro_file", "ar ...

  5. 黄聪:Discuz X2.5、3.0、3.1、3.2 如何不用插件实现用户名只允许中文注册

    1.在后台--注册与访问--注册链接文字,把“注册”改为“中文注册”或“注册(请使用中文注册)”等   2.后台UCenter管理中心---注册设置---禁止的用户名:   *q* *w* *e* * ...

  6. TCP非阻塞通信

    一.SelectableChannel SelectableChannel支持阻塞和非阻塞模式的channel 非阻塞模式下的SelectableChannel,读写不会阻塞 SelectableCh ...

  7. HttpUrlConnection java.net.SocketException: Software caused connection abort: recv failed

    最近做java swing程序在模拟httprequest请求的时候出现了这个错误 java.net.SocketException: Software caused connection abort ...

  8. 洛谷 P1060 开心的金明

    开心的金明 Problem Description: 金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间他自己专用的很宽敞的房间.更让他高兴的是,妈妈昨天对他说:"你的房间需要购买哪些 ...

  9. input file 上传文件

    面试的时候遇到一个问题,要求手写的方式上传文件. 本来觉得很简单,但是结果怎么也成功不了. 前台: <form ID="form1" action="AcceptF ...

  10. centos6.5安装mysql记录

    1.查看操作系统相关信息. [root@linuxidc ~]# cat /etc/issue CentOS release 6.5 (Final) Kernel \r on an \m [root@ ...