原文位址:http://www.worlduc.com/blog2012.aspx?bid=459878
程式主界面:

項目根目錄下放一個TextFile.txt和一個字元串專題.doc檔案
當我們點下“檢視文本檔案”按鈕時可以看到:
會輸出TextFile.txt的内容:
當我們點“檢視doc檔案”按鈕的時候會:
當我們點打開:會看到doc檔案裡的内容包括格式和内容都不會變:
其兩個按鈕的單擊事件的源碼為:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.WriteFile("TextFile.txt");
}
protected void Button2_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~/字元串專題.doc");//檔案的路徑
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset = "utf-8";//設定輸出的編碼
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加頭資訊,為"檔案下載下傳/另存為"對話框指定預設檔案名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加頭資訊,指定檔案大小,讓浏覽器能夠顯示下載下傳進度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定傳回的是一個不能被用戶端讀取的流,必須被下載下傳
Response.ContentType = "application/msword";
// 把檔案流發送到用戶端
Response.WriteFile(file.FullName);
Response.End();
// Response.WriteFile("test.doc");
}
也可用下面的方法直接打開檔案:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "", "window.open('" + string_FileRelativePath + "', '_blank');", true);