栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#实现word文件下载的代码

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#实现word文件下载的代码

效果:

思路:

简单的有两种方式下载,一种是流下载,一种是WriteFile下载。以下是使用WriteFile下载。

代码:

复制代码 代码如下:
protected void linkButton1_Click(object sender, EventArgs e)
        {
            try
            {
                //WriteFile实现下载(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();

        }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/126848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号