一切福田,不離方寸,從心而覓,感無不通。

在ASP.NET中下载Text文件,而不是在浏览器中打开它

介绍

让用户从我们的网站上下载各种类型的文件是一个比较常用的功能,这篇文章就是告诉您如何创建一个.txt文件并让用户下载。

使用代码

虽然在示例里,我先创建了一个text文件,但是你不一定也要这么做,因为这个文件可能在你的网站里已经存在了。如果是这样的话,你只需要使用FileStream去读取它就可以了。

首先,我们将这个text文件读取到一个byte数组中,然后使用Response对象将文件写到客户端就可以了。

Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();

这段代码是完成这个功能的主要代码。第一句在输出中添加了一个Header,告诉浏览器我们发送给它的是一个附件类型的文件。然后我们设置输出的ContentType是"application/octet-stream",即告诉浏览器要下载这个文件,而不是在浏览器中显示它。

下面是一个MIME类型的列表。

".asf" = "video/x-ms-asf"
".avi" = "video/avi"
".doc" = "application/msword"
".zip" = "application/zip"
".xls" = "application/vnd.ms-excel"
".gif" = "image/gif"
".jpg"= "image/jpeg"
".wav" = "audio/wav"
".mp3" = "audio/mpeg3"
".mpg" "mpeg" = "video/mpeg"
".rtf" = "application/rtf"
".htm", "html" = "text/html"
".asp" = "text/asp"

'所有其它的文件
= "application/octet-stream"

下面是一个完整的如何下载文本文件的示例代码
C#

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, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
}
VB.NET

Dim strFileName As String = System.IO.Path.GetRandomFileName()
Dim strFriendlyName As String = "Friendly.txt"

Using sw As New System.IO.StreamWriter(Server.MapPath("TextFiles/" + strFileName + ".txt"))
sw.WriteLine(txtText.Text)
sw.Close()
End Using

Dim fs As System.IO.FileStream = Nothing

fs = System.IO.File.Open(Server.MapPath("TextFiles/" + strFileName + ".txt"), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
.AddHeader("Content-disposition", "attachment;filename=" & strFriendlyName)
.ContentType = "application/octet-stream"
.BinaryWrite(btFile)
.End()
End With

小结
使用这个方法,你可以实现在Windows系统下下载所有的文件类型。但是在Macintosh系统下会有些问题。

 

from:http://blog.itpub.net/36095/viewspace-920753/