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.
FileSaveDialog
? – Vtarjusing
statement? – Gloveusing
statement when you're writing to the file. Take a look at my answer. Do you really need to have aMemoryStream
? You can just have astring
(StringBuilder
, to be more specific) and append lines to it, and when you decide to write it to the file (after the user selects a output file in theSaveFileDialog
, or when clicks on Save button,...), you write thatstring
to the file. Then you won't have any problem with theusing
. – Glove