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

10,730

Solution 1

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

Solution 2

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 MSDN for a good example of how to set one up.

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

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 handler page. The code would be almost identical.

Solution 3

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?

Solution 4

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

Share:
10,730
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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?