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")

ASP.NET 保存txt文件,布布扣,bubuko.com

ASP.NET 保存txt文件

上一篇:LAMP编译安装(fpm方式连接PHP和HTTPD)


下一篇:调试WebService