Crear un archivo .txt si no existe, y si existe añadir una nueva línea

Me gustaría crear un archivo .txt y escribir en él, y si el archivo ya existe sólo quiero añadir algunas líneas más:

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(); 
}

Pero la primera línea parece que siempre se sobrescribe... ¿cómo puedo evitar escribir en la misma línea (estoy usando esto en un bucle)?

Sé que es algo muy sencillo, pero nunca he utilizado el método WriteLine. Soy totalmente nuevo en C#.

Solución

Utilice el constructor correcto:

else if (File.Exists(path))
{
    using(var tw = new StreamWriter(path, true))
    {
        tw.WriteLine("The next line!");
    }
}
Comentarios (5)

Sólo quieres abrir el archivo en modo "append".

http://msdn.microsoft.com/en-us/library/3zc0w663.aspx

Comentarios (1)

Puedes utilizar un FileStream. Esto hace todo el trabajo por ti.

http://www.csharp-examples.net/filestream-open-file/

Comentarios (0)