问题描述:后台生成了文本文件,用超链接提供给用户下载。点击超链接,下载Excel文件没问题,但文本文件会直接被打开,而不是弹出下载窗口。
解决方法:把HyperLink改为LinkButton,在Click事件中,用文件流写文本文件。
关键代码:
protected void Button1_Click(object sender, EventArgs e)
{
string sFileName = System.IO.Path.GetRandomFileName();
string sGenName = "Friendly.txt"; //YOu could omit these lines here as you may
//not want to save the textfile to the server
//I have just left them here to demonstrate that you could create the text file
using (System.IO.StreamWriter SW = new System.IO.StreamWriter(
Server.MapPath("TextFiles/" + sFileName + ".txt")))
{
SW.WriteLine(txtText.Text);
SW.Close();
} System.IO.FileStream fs = null;
fs = System.IO.File.Open(Server.MapPath("TextFiles/" +
sFileName + ".txt"), System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, , Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" +
sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
}
参考文档:http://www.codeproject.com/useritems/textfile.asp