ASP.NET 保存txt文件


 public void ProcessRequest(HttpContext context)
        {

            context.Response.Clear();
            context.Response.Buffer = true;
            //Server.UrlEncode 防止保存的文件名亂碼
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode("消費明細" + string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + ".txt"));   
            context.Response.ContentType = "text/plain";  
            string message = "Hello World";
            //如果導出的文件要換行,用Environment.NewLine
            message += "Hello World" + Environment.NewLine;
            context.Response.Write(message);
            //停止頁面的執行     
            context.Response.End(); 
        }

注意兩點:

1.保存文件名亂碼問題:用Server.UrlEncode編碼

2.txt文件中的換行問題:Environment.NewLine

3.調用可以用js:window.location.href="download.ashx" 或window.open("download.ashx")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM