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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/898145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 22:04:54  来源:igfitidea点击:

In ASP.NET, how to get the browser to download string content into a file? (C#)

c#asp.netfilecsvexport

提问by

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?

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

回答by Joel Coehoorn

A file you haven't saved yet is just a string variable or a MemoryStream. But for large amounts of data you probably don't want to keep it all in memory. What do you want to do with this "file" once you have it?

您尚未保存的文件只是一个字符串变量或 MemoryStream。但是对于大量数据,您可能不想将其全部保存在内存中。一旦你有了这个“文件”,你想用它做什么?

回答by Cheeso

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

引用:RFC 4180

回答by CMS

You could write direcly to the Response.OutputStreamand set the right content type, and content disposition header.

您可以直接写入Response.OutputStream并设置正确的内容类型和内容处置标头。

回答by JasonRShaver

Oh, that is not bad. In your ASPX page's Page_Load do this:

哦,那还不错。在您的 ASPX 页面的 Page_Load 中执行以下操作:

Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(/* your text goes here */);

The above is an example if your 'file' is xml, but it can be anything, from and excel file to a pdf. All you have to do is update the ContentType which you can lookup via Google or Live.

上面是一个例子,如果你的“文件”是 xml,但它可以是任何东西,从 excel 文件到 pdf。您所要做的就是更新您可以通过 Google 或 Live 查找的 ContentType。

回答by NinethSense

Try this sample:

试试这个示例:

protected void Button1_Click(object sender, EventArgs e)
{
     Response.ContentType = "text/csv";
     Response.AddHeader("content-disposition", "attachment; filename=download.csv");
     Response.Write("your,csv,file,contents");
     Response.End();
}

回答by Noldorin

You'll want to look at writing a Custom HTTP Handler(a class that implements IHttpHandler) and simply register it in web.config. See this article on MSDNfor a good example of how to set one up.

您需要考虑编写一个自定义 HTTP 处理程序(一个实现 的类IHttpHandler)并简单地在 web.config 中注册它。有关如何设置的一个很好的示例,请参阅MSDN 上的这篇文章

Here's a basic example of how you might go about implementing one to return the markup for some CSV data.

下面是一个基本示例,说明如何实现一个返回某些 CSV 数据标记的方法。

using System.Web;

public class MyCsvDocumentHandler : IHttpHandler
{
    public static string Data
    {
        get;
        set;
    }

    public MyCsvDocumentHandler()
    {
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/csv"; // Set the MIME type.
        context.Response.Write(Data); // Write the CSV data to the respone stream.
    }

    public bool IsReusable
    {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }
    }
}

This alternative, which is possibly slightly simpler, is to use an ASHX handlerpage. The code would be almost identical.

这种可能稍微简单的替代方法是使用ASHX 处理程序页面。代码几乎相同。