C#實現(xiàn)word文件下載的代碼
效果:

思路:
簡單的有兩種方式下載,一種是流下載,一種是WriteFile下載。以下是使用WriteFile下載。
代碼:
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
//WriteFile實現(xiàn)下載(word)
string fileName = "qingpingguo.docx";//客戶端保存的文件名
string filePath = Server.MapPath("~\\excel\\" + tb1.Text);//路徑
FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
/*************以下為流方式下載****************/
//string fileName = "aaa.txt";//客戶端保存的文件名
//string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑
////以字符流的形式下載文件
//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);
//Response.Flush();
//Response.End();
}
相關(guān)文章
c#高效的線程安全隊列ConcurrentQueue<T>的實現(xiàn)
這篇文章主要介紹了c#高效的線程安全隊列ConcurrentQueue<T>的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
C#使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間
這篇文章主要為大家詳細介紹了C#如何使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考下2024-01-01
淺談C#2.0泛型中的變化:default關(guān)鍵字
下面就詳細的說明一下。之所以會用到default關(guān)鍵字,是因為需要在不知道類型參數(shù)為值類型還是引用類型的情況下,為對象實例賦初值2013-09-09
.net文件上傳時實現(xiàn)通過文件頭確認文件類型的方法
這篇文章主要介紹了.net文件上傳時實現(xiàn)通過文件頭確認文件類型的方法,很實用的功能,需要的朋友可以參考下2014-07-07
基于C#的winform實現(xiàn)數(shù)字華容道游戲
這篇文章主要為大家詳細介紹了基于C#的winform實現(xiàn)數(shù)字華容道游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02

