.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+"
";
            }
            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