下载文件时提示\"无法复制文件,无法读取文件或磁盘\"的错误解决方案
下载文件时提示”无法复制文件,无法读取文件或磁盘”的错误解决方案
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
namespace infoPlatClient.NetDisk
{
public partial class downLoad : Com.DRPENG.Common.WebStruct.BaseForm
{
/// <summary>
/// 取得要下载文件的路径
/// </summary>
private string fileRpath
{
get
{
return Request[“fileRpath”] == null ? “” : Request[“fileRpath”];
}
}
/// <summary>
/// 取得要下载文件的名称
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
DownLoad();
}
private void DownLoad()
{
string name = System.IO.Path.GetFileName(fileRpath);
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileRpath);
if (fileInfo.Exists == true)
{
const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
byte[] buffer = new byte[ChunkSize];
Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(fileRpath);
long dataLengthToRead = iStream.Length;//获取下载的文件总大小
Response.ContentType = “application/octet-stream;charset=gbk”;
Response.AddHeader(“Content-Disposition”, “attachment;filename=” + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead – lengthRead;
}
Response.Close();
}
}
}
}
主要是这段代码: Response.ContentType = “application/octet-stream;charset=gbk”;