higgsy higgsy - 1 year ago 73
ASP.NET (C#) Question

Create text file and download

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

to write the contents:

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

How do I then download this file?

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)));

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download