在ASP.NET中,如何获取浏览器将字符串内容下载到文件中? (C#)

问题描述:

我想从ASP.NET应用程序创建一个用于导出/下载的文本文件,例如* .csv。我知道 Response.TransmitFile ,但我想这样做,而不是在服务器上物理地创建和保存文件。那可能吗?
有人做过这样的事吗?

I would like to create a text file for export/download, like a *.csv, from an ASP.NET application. I know about Response.TransmitFile, but I want to do this without creating and saving a file physically on the server. Is that possible? Has anyone done something like that?

当你说创建一个文件导出你想让它下载到浏览器。如果是这样,下面是一个例子。

When you say "Create a file for export", I am understanding that you want to make it downloadable to the browser. If that's the case, here's an example.

public void btnGo_Click (Object sender, EventArgs e)
{
    Response.Clear();

    string fileName= String.Format("data-{0}.csv", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); 
    Response.ContentType = "text/csv";
    Response.AddHeader("content-disposition", "filename=" + fileName);

    // write string data to Response.OutputStream here
    Response.Write("aaa,bbb,ccc\n");

    Response.End();
}

cite: RFC 4180