asp.net 文件下载功能函数代码整理
更新时间:2010年04月03日 16:54:35 作者:
asp.net下文件下载功能代码,fullFilename 要下载的文件的路径+文件名,需要的朋友可以参考下。
复制代码 代码如下:
public void FileDownLoadDel(string fullFilename)
{
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = fullFilename;
filepath = Server.MapPath(filepath);
// 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;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
Response.Clear();
}
}
Response.End(); //没有这句会将该页面刷新后的内容追加写入文件中。
}
catch (Exception ex)
{
// Trap the error, if any.
//Response.Write("Error : " + ex.Message);
//base.WriteLog("资料", "下载资料:" + ex.Message + "!", LogType.Error, this.GetType().ToString());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
File.Delete(fullFilename);
}
}
相关文章
.NET Core类库项目中读取appsettings.json配置的方法
ASP.NET Core是一个全新的Web开发平台,微软在它上面构建了MVC、SingalR、GRPC、Orleans这样广泛使用的Web框架,今天通过本文给大家详细介绍下.NET Core读取appsettings.json配置的方法,感兴趣的朋友一起看看吧2022-03-03
如何处理ASP.NET Core中HTML5客户端路由回退的问题
这篇文章主要给大家介绍了关于如何处理ASP.NET Core中HTML5客户端路由回退的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。2017-11-11
.Net笔记:System.IO之windows文件操作的深入分析
本篇文章是对.Net中windows文件操作的使用进行了详细的分析介绍,需要的朋友参考下2013-05-05


最新评论