I would like to create a .txt file and write to it, and if the file already exists I just want to append some more lines:
string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine("The very first line!");
tw.Close();
}
else if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path);
tw.WriteLine("The next line!");
tw.Close();
}
But the first line seems to always get overwritten... how can I avoid writing on the same line (I'm using this in a loop)?
I know it's a pretty simple thing, but I never used the WriteLine
method before. I'm totally new to C#.
When you start StreamWriter it's override the text was there before. You can use append property like so:
You could use a FileStream. This does all the work for you.
http://www.csharp-examples.net/filestream-open-file/
Try this.
You just want to open the file in "append" mode.
http://msdn.microsoft.com/en-us/library/3zc0w663.aspx