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\\Examp
string path = @"E:\AppServ\Example.txt";
File.AppendAllLines(path, new [] { "The very first line!" });
See also File.AppendAllText(). AppendAllLines will add a newline to each line without having to put it there yourself.
Both methods will create the file if it doesn't exist so you don't have to.
You could use a FileStream. This does all the work for you.
http://www.csharp-examples.net/filestream-open-file/
File.AppendAllText adds a string to a file. It also creates a text file if the file does not exist. If you don't need to read content, it's very efficient. The use case is logging.
File.AppendAllText("C:\\log.txt", "hello world\n");
else if (File.Exists(path))
{
using (StreamWriter w = File.AppendText(path))
{
w.WriteLine("The next line!");
w.Close();
}
}
You don't actually have to check if the file exists, as StreamWriter will do that for you. If you open it in append-mode, the file will be created if it does not exists, then you will always append and never over write. So your initial check is redundant.
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("The next line!");
tw.Close();
When you start StreamWriter it's override the text was there before. You can use append property like so:
TextWriter t = new StreamWriter(path, true);