C# - Append to a text file

Hi,

Lets say I have a text file.

Always when I try to write to it with the following code, It erases what was already in it:

                // create a writer and open the file
                TextWriter tw = new StreamWriter(MyTextfile.txt);

                // write a line of text to the file
                tw.WriteLine(msg);

                // close the stream
                tw.Close();

How can I write to a text file so I only add text to it (I don't delete the text that was already in the text file)?

Thank you.
EndelmAsked:
Who is Participating?
 
gregoryyoungConnect With a Mentor Commented:
0
 
gregoryyoungCommented:
TextWriter tw = new StreamWriter(MyTextfile.txt, true); http://msdn2.microsoft.com/en-us/library/36b035cb.aspx
0
 
EndelmAuthor Commented:
thank you.
0
 
feradzCommented:
Use constructor StreamWriter(string path, bool append);
example is given below
StreamWriter sw = new StreamWriter(@"C:\mydir\myfile.txt", true);
sw.WriteLine("Some lines");
sw.Close();

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.