欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-18 22:36:22
效果: 思路: 简单的有两种方式下载,一种是流下载,一种是writefile下载。以下是使用writefile下载。 代码: 复制代码 代码如下:protect...

效果:

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();

        }