7

I'm using C# and ASP.NET 2.5.

I want a simple way to generate a "file" on-the-fly (let's say a csv file for this example) and transmit it to the client without actually writing it to the server file system.

1
  • Total sidenote: Am I nuts, or is the latest version of ASP.NET 2.0? .NET is up to 3.5 SP1, but I thought ASP.NET was at 2.0 Jun 19, 2009 at 17:30

3 Answers 3

10

After some searching and trial and error, I developed the following. It seems to fit the bill exactly. It should be very easily adaptable to PHP or any other server-side software since it mostly involves modifying headers.

protected void streamToResponse()
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=testfile.csv");
    Response.AddHeader("content-type", "text/csv");

    using(StreamWriter writer = new StreamWriter(Response.OutputStream))
    {
        writer.WriteLine("col1,col2,col3");
        writer.WriteLine("1,2,3");
    }
    Response.End();
}
2
  • Yes, this is a good approach; however, this code should reside inside an ashx file. In visual studio its called a "Generic Handler" this reduced the overhead of loading an aspx page.
    – Nate
    Jun 17, 2009 at 18:37
  • Nate, in the case where I used this I had an "Export Report" button that was, basically, the function above. Should the button instead have somehow used an ashx?
    – Eric
    Jun 17, 2009 at 18:39
2

May I also suggest, that if you have something other than text, say, binary, you use the Response.WriteBinary() method

I've often created a JPG on the fly, wrote it to a MemoryStream using the Bitmap.Save() method, turned the MemoryStream into a byte[] array using .ToArray() and then Response.WriteBinary() that array.

0

Use the MemoryStream Class:

http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.