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();
Another way to create a text file is to right-click an empty area on the desktop, and in the pop-up menu, select New, and then select Text Document. Creating a text file this way opens your default text editor with a blank text file on your desktop. You can change the name of the file to anything you want.
In a Windows Microsoft Word document, click the Save As button from the File menu. Select Save As Type from the drop-down list then select Plain Text (*. txt). Click the Save button and a File Conversion window will open.
The correct way to do it would be: <? php $file = "test. txt"; $txt = fopen($file, "w") or die("Unable to open file!"); fwrite($txt, "lorem ipsum"); fclose($txt); header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename='.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With