Stream下载文件取消后再点击下载文件被占用

ssq4706 2011-12-28 09:19:32
代码如下:
context.Response.ContentType = "text/plain";
string filePath = context.Request.Params["path"];//文件相对路径
if (FileExists(context.Server.MapPath(filePath)))
{
// 允许共享
System.IO.Stream input = new System.IO.FileStream(context.Server.MapPath(filePath), System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Inheritable);
context.Response.ContentType = "application/octet-stream";
//文件名
string fileName = System.IO.Path.GetFileName(filePath);
//文件名编码
string encodingFileName = context.Server.UrlEncode(fileName).Replace('+', ' ');
context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", encodingFileName));
// 输出到 this.Response.OutputStream 中
System.IO.Stream output = context.Response.OutputStream;
// 创建一个块缓冲
byte[] buffer = new byte[10 * 1024];
// 手工关闭输出的缓存
context.Response.BufferOutput = false;
TransmitFile(input, output, buffer);
output.Close();
input.Close();
context.Response.End();
}

问题是点击下载,弹出下载对话框,取消,再点击下载,报错,文件被进程占用。该怎么改进,谢谢!
...全文
152 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
ssq4706 2011-12-28
  • 打赏
  • 举报
回复

/// <summary>
/// 传输文件
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="buffer"></param>
private void TransmitFile(System.IO.Stream input, System.IO.Stream output, byte[] buffer)
{
int length = 0;
while ((length = input.Read(buffer, 0, buffer.Length)) > 0)
{
// 写出
output.Write(buffer, 0, length);
}
}
jiezi316 2011-12-28
  • 打赏
  • 举报
回复
Response.TransmitFile(string filename)

简单好用!
SomethingJack 2011-12-28
  • 打赏
  • 举报
回复
[Quote=引用楼主 ssq4706 的回复:]
代码如下:C# code
context.Response.ContentType = "text/plain";
string filePath = context.Request.Params["path"];//文件相对路径
if (FileExists(context.Server.MapPath(filePath)))
……
[/Quote]

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace Asiastar.NR.Ajax
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";

string id = context.Request["id"].ToString();//获取资源的编号
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
NRBLL.File bf = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
if (bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"] != null)//判断数据库路径是否存在
{
string filepath = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString();//获取资源完整路径 D:\资源文件\600cc139-14cf-448e-9e50-daa972d35e01.jpg
string Oidfilename = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FileNam"].ToString();//旧文件名称
//string filename = System.IO.Path.GetFileName(filepath);//获取文件名称+后缀名 600cc139-14cf-448e-9e50-daa972d35e01.JPG
//int index = filepath.IndexOf(".");
//string filetype = filepath.Substring(index).ToLower();//后缀名
//string newfilename = Oidfilename;
//string filepath1 = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString().Substring(0,filepath.Length - 8);
try
{
string fileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Oidfilename));//解码(注意这里2层解码)
Oidfilename = Oidfilename.Replace("+", "%20"); //将“+”替换成“空格”
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Oidfilename, System.Text.Encoding.UTF8)); //下载的时候下载原来的文件名称
while (dataToRead > 0)
{
if (context.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
context.Response.OutputStream.Write(buffer, 0, length);
context.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}

}
catch (Exception ex)
{
NR.Error.Log.LogType(ex.ToString());
}
finally
{
if (iStream != null)
{
iStream.Close();
}
}
}
else
{
NR.Error.Log.LogType("找不到文件!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
机器人 2011-12-28
  • 打赏
  • 举报
回复
TransmitFile(input, output, buffer);

怎么实现的?我记得 Response.TransmitFile 只有一个参数: FileName。
且是不缓存直接输出到客户端的。

如果文件不是太大,完全可以直接用 Response.TransmitFile 也不要自己用 FileStream 打开文件。

另外,注意你 FileStream 的最后一个参数: System.IO.FileShare.Inheritable
如果是可读的话应该是 System.IO.FileShare.Read ,且你只是下载,FileAccess用不着ReadWrite吧

俗人1979 2011-12-28
  • 打赏
  • 举报
回复
System.IO.Stream input = new System.IO.FileStream(context.Server.MapPath(filePath), System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Inheritable);

改成这样试试:
System.IO.Stream input = new System.IO.FileStream(context.Server.MapPath(filePath), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
机器人 2011-12-28
  • 打赏
  • 举报
回复
TransmitFile(input, output, buffer);

怎么实现的?我记得 Response.TransmitFile 只有一个参数: FileName。
且是不缓存直接输出到客户端的。

如果文件不是太大,完全可以直接用 Response.TransmitFile 也不要自己用 FileStream 打开文件。

另外,注意你 FileStream 的最后一个参数: System.IO.FileShare.Inheritable
如果是可读的话应该是 System.IO.FileShare.Read

jiezi316 2011-12-28
  • 打赏
  • 举报
回复
为什么不直接用

Response.TransmitFile(string filename)
SomethingJack 2011-12-28
  • 打赏
  • 举报
回复
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace Asiastar.NR.Ajax
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";

string id = context.Request["id"].ToString();//获取资源的编号
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
NRBLL.File bf = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
if (bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"] != null)//判断数据库路径是否存在
{
string filepath = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString();//获取资源完整路径 D:\资源文件\600cc139-14cf-448e-9e50-daa972d35e01.jpg
string Oidfilename = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FileNam"].ToString();//旧文件名称
//string filename = System.IO.Path.GetFileName(filepath);//获取文件名称+后缀名 600cc139-14cf-448e-9e50-daa972d35e01.JPG
//int index = filepath.IndexOf(".");
//string filetype = filepath.Substring(index).ToLower();//后缀名
//string newfilename = Oidfilename;
//string filepath1 = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString().Substring(0,filepath.Length - 8);
try
{
string fileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Oidfilename));//解码(注意这里2层解码)
Oidfilename = Oidfilename.Replace("+", "%20"); //将“+”替换成“空格”
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Oidfilename, System.Text.Encoding.UTF8)); //下载的时候下载原来的文件名称
while (dataToRead > 0)
{
if (context.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
context.Response.OutputStream.Write(buffer, 0, length);
context.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}

}
catch (Exception ex)
{
NR.Error.Log.LogType(ex.ToString());
}
finally
{
if (iStream != null)
{
iStream.Close();
}
}
}
else
{
NR.Error.Log.LogType("找不到文件!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
SomethingJack 2011-12-28
  • 打赏
  • 举报
回复
下载
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace Asiastar.NR.Ajax
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";

string id = context.Request["id"].ToString();//获取资源的编号
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
NRBLL.File bf = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
if (bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"] != null)//判断数据库路径是否存在
{
string filepath = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString();//获取资源完整路径 D:\资源文件\600cc139-14cf-448e-9e50-daa972d35e01.jpg
string Oidfilename = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FileNam"].ToString();//旧文件名称
//string filename = System.IO.Path.GetFileName(filepath);//获取文件名称+后缀名 600cc139-14cf-448e-9e50-daa972d35e01.JPG
//int index = filepath.IndexOf(".");
//string filetype = filepath.Substring(index).ToLower();//后缀名
//string newfilename = Oidfilename;
//string filepath1 = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString().Substring(0,filepath.Length - 8);
try
{
string fileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Oidfilename));//解码(注意这里2层解码)
Oidfilename = Oidfilename.Replace("+", "%20"); //将“+”替换成“空格”
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Oidfilename, System.Text.Encoding.UTF8)); //下载的时候下载原来的文件名称
while (dataToRead > 0)
{
if (context.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
context.Response.OutputStream.Write(buffer, 0, length);
context.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}

}
catch (Exception ex)
{
NR.Error.Log.LogType(ex.ToString());
}
finally
{
if (iStream != null)
{
iStream.Close();
}
}
}
else
{
NR.Error.Log.LogType("找不到文件!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧