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();
}
相關文章
C#線性漸變畫刷LinearGradientBrush用法實例
這篇文章主要介紹了C#線性漸變畫刷LinearGradientBrush用法,實例分析了線性漸變畫刷LinearGradientBrush的相關使用技巧,需要的朋友可以參考下2015-06-06
C#使用DateAndTime.DateDiff實現(xiàn)計算年齡
這篇文章主要為大家詳細介紹了C#如何使用DateAndTime.DateDiff實現(xiàn)根據(jù)生日計算年齡,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2024-01-01
VS2019下安裝和破解?DevExpress?19.2?插件的詳細教程
這篇文章主要介紹了VS2019?安裝并破解?DevExpress?19.2?插件的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03

