Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Text File in memory and saving it with savefiledialog

I am trying to make a text file in memory, add some lines to it and at the end save the file in a text file. I can handle the savedialog part but I dont know how to get the text file from memory. Any help and tips will be appriciated.

What I am doing so far is:

//Initialize in memory text writer
MemoryStream ms = new MemoryStream(); 
TextWriter tw = new StreamWriter(ms);

tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);

please note I will call tw.WriteLine() add more lines in different places so I want to save this at end of program (so this shouldent be wrapped between something like using{} )

UPDATE

StringBuilder seems to be a more reliable option for doing this! I get strange cut-outs in my text file when I do it using MemoryStream.

Thanks.

like image 550
Saeid Yazdani Avatar asked Apr 18 '11 12:04

Saeid Yazdani


People also ask

How to Save a file with SaveFileDialog?

To save a file using the SaveFileDialog component. Display the Save File dialog box and call a method to save the file selected by the user. Use the SaveFileDialog component's OpenFile method to save the file. This method gives you a Stream object you can write to.

How do I save SaveFileDialog in VB net?

The SaveFileDialog control prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data. The SaveFileDialog control class inherits from the abstract class FileDialog.


1 Answers

I think your best option here would be to write to a StringBuilder, and when done, File.WriteAllText. If the contents are large, you might consider writing directly to the file in the first place (via File.CreateText(path)), but for small-to-medium files this should be fine.

var sb = new StringBuilder();

sb.AppendLine("HELLO WORLD!");
sb.AppendLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");

File.WriteAllText(path, sb.ToString());
like image 83
Marc Gravell Avatar answered Sep 19 '22 06:09

Marc Gravell