views:

647

answers:

3

Is there any way to take a StreamWriter and output the file (in this case a .txt file) to the user with the option to open/save without actually writing the file to disk? If it is not saved it will basically go away.

I am looking for the same functionality of

HttpContext.Current.Response.TransmitFile(file);

but without having to save anything to disk. Thanks!

+5  A: 

Try a System.IO.MemoryStream

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
sw.Write("hello");
Spence
+1  A: 

I've done this recently for a XML file, Should be easy for you to adapt

protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=myfile.xml");
            Response.ContentType = "text/xml";
            UTF8Encoding encoding = new UTF8Encoding();
            Response.BinaryWrite(encoding.GetBytes("my string"));
            Response.Flush();
            Response.End();
        }
Sergio
+1  A: 

or use Response.BinaryWrite(byte[]);

Response.AppendHeader("Content-Disposition", @"Attachment; Filename=MyFile.txt");              
Response.ContentType = "plain/text";    
Response.BinaryWrite(textFileBytes);

Something like that should work. If you have the text file in a stream you can easily get the byte[] out of it.

EDIT: See above, but change the ContentType obvoisly.

Findel_Netring