Create text file and download

68,742

Solution 1

Instead of storing the data in memory and then sending it to the response stream, you can write it directly to the response stream:

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
  writer.Write("This is the content");
}

The example uses the UTF-8 encoding, you should change that if you are using some other encoding.

Solution 2

This solved for me:

        MemoryStream ms = new MemoryStream();
        TextWriter tw = new StreamWriter(ms);
        tw.WriteLine("Line 1");
        tw.WriteLine("Line 2");
        tw.WriteLine("Line 3");
        tw.Flush();
        byte[] bytes = ms.ToArray();
        ms.Close();

        Response.Clear();
        Response.ContentType = "application/force-download";
        Response.AddHeader("content-disposition", "attachment;    filename=file.txt");
        Response.BinaryWrite(bytes);
        Response.End();     

Solution 3

Basically you create an HttpHandler by implementing the IHttpHandler interface. In the ProcessRequest method you basically just write your text to context.Response. You also need to add a Content-Disposition http header:

context.Response.AddHeader("Content-Disposition", "attachment; filename=YourFileName.txt");

Also remember to set the ContentType:

context.Response.ContentType = "text/plain";

Solution 4

Just a small addition to the other answers. At the very end of a download I execute:

context.Response.Flush();
context.ApplicationInstance.CompleteRequest();

I learned that otherwise, the download sometimes does not complete successfully.

This Google Groups posting also notes that Response.End throws a ThreadAbortException which you could avoid by using the CompleteRequest method.

Share:
68,742
higgsy
Author by

higgsy

Updated on February 08, 2020

Comments

  • higgsy
    higgsy about 4 years

    I'm trying to write to a text file in memory and then download that file without saving the file to the hard disk. I'm using the StringWriter to write the contents:

    StringWriter oStringWriter = new StringWriter();
    oStringWriter.Write("This is the content");
    

    How do I then download this file?

    EDIT: It was combination of answers which gave me my solution. Here it is:

    StringWriter oStringWriter = new StringWriter();
    oStringWriter.WriteLine("Line 1");
    Response.ContentType = "text/plain";
    
    Response.AddHeader("content-disposition", "attachment;filename=" + string.Format("members-{0}.csv",string.Format("{0:ddMMyyyy}",DateTime.Today)));
    Response.Clear();
    
    using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
    {
        writer.Write(oStringWriter.ToString());
    }
    Response.End();