Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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(); 
like image 894
higgsy Avatar asked Dec 31 '10 13:12

higgsy


People also ask

How do you create a text file and save it?

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.

How do you create a plain text file?

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.

How do I create a .TXT file and download in PHP?

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='.


1 Answers

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();      
like image 127
VINICIUS SIN Avatar answered Sep 21 '22 20:09

VINICIUS SIN