ASP.NET 保存txt文件

时间:2023-03-08 18:08:09
 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")