用C#在网页上实现文件下载,多种方法均不成功,求解!谢谢
DownFiletbl.Rows[e.NewEditIndex].Cells[9].Text为文件路径;
具体代码如下:
1、第1种方法:
string fileRpath = DownFiletbl.Rows[e.NewEditIndex].Cells[9].Text;
Response.ClearHeaders();
Response.Clear();
Response.Expires = 0;
Response.Buffer = true;
Response.AddHeader("Accept-Language", "zh-tw");
string name = System.IO.Path.GetFileName(fileRpath);
System.IO.FileStream files = new FileStream(fileRpath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] byteFile = null;
if (files.Length == 0)
{
byteFile = new byte[1];
}
else
{
byteFile = new byte[files.Length];
}
files.Read(byteFile, 0, (int)byteFile.Length);
files.Close();
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
Response.ContentType = "application/octet-stream;charset=gbk";
Response.BinaryWrite(byteFile);
Response.End();
2、第2种方法:
string path = DownFiletbl.Rows[e.NewEditIndex].Cells[9].Text;
var vPos = path.IndexOf("\\files");
path = path.Substring(vPos + 1, path.Length - vPos - 1);
string fileName = "aaaa.txt";//客户端保存的文件名
string filePath = Server.MapPath(path);//路径
try
{
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);