.NET 在浏览器中下载TXT文件

 通常我们用浏览器打开Txt文件时候,浏览器会直接打开,我们想要txt下载到本地该怎么操作,用js也可以,单不能兼容所有的浏览器,所以我们可以在服务端做处理,代码如下:

        //TXT文件生成页面
        public ActionResult FileDownLoad(string filepth)
        {
            string FileCompath= Server.MapPath(filepth);
            string Result = "";
            StreamReader strmer = new StreamReader(FileCompath, Encoding.Default);             
            string  linetext;
            while ((linetext = strmer.ReadLine()) != null)
            {
                Result += linetext+"\r\n";
            }
            strmer.Close();
            Response.Headers["Content-Disposition"] = "attachment;filename=aaa.txt";//输出文件格式
            Response.Charset = "utf-8";//防止乱码
            Response.Write(Result);
            return View();
        }

文件打开,记得关闭以释放资源;

 

 public ActionResult FileDownLoad(string filepth)
        {
            string FileCompath= Server.MapPath(filepth);
       System.IO.FileStream fs = null;
            fs = System.IO.File.Open(FileCompath, System.IO.FileMode.Open);
            byte[] btFile = new byte[fs.Length];
            fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            Response.Headers["Content-Disposition"] = "attachment;filename=aaa.pdf";//输出文件格式
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(btFile);
       
       return View();
   }

 

转载于:https://www.cnblogs.com/xibei666/p/5559148.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值