C# - Append to a text file

Posted on 2007-11-15
Medium Priority
Last Modified: 2013-11-07

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

                // close the stream

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.
Question by:Endelm
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
LVL 37

Expert Comment

ID: 20291428
TextWriter tw = new StreamWriter(MyTextfile.txt, true); http://msdn2.microsoft.com/en-us/library/36b035cb.aspx
LVL 37

Accepted Solution

gregoryyoung earned 2000 total points
ID: 20291443

Author Closing Comment

ID: 31409399
thank you.

Expert Comment

ID: 20760757
Use constructor StreamWriter(string path, bool append);
example is given below
StreamWriter sw = new StreamWriter(@"C:\mydir\myfile.txt", true);
sw.WriteLine("Some lines");

Open in new window


Featured Post

Stack Overflow Podcast - Frustrating Miracles

In this podcast, Stack Overflow interviewed Linux Academy CEO/Founder, Anthony James, and got his developer story!

"Follow your passion, be prepared to work hard and sacrifice, and, above all, don't let anyone limit your dreams."  - Donovan Bailey

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that undeā€¦
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question