Criar um arquivo .txt se não't existir, e se ele anexar uma nova linha

Eu gostaria de criar um arquivo .txt e escrever nele, e se o arquivo já existe eu só quero anexar mais algumas linhas:

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

Mas a primeira linha parece ser sempre sobrescrita... como posso evitar escrever na mesma linha (I'm usando isto em loop)?

Eu sei disso'é uma coisa bem simples, mas eu nunca usei o método WriteLine antes. I'sou totalmente novo no C#.

Solução

Use o construtor correto:

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

Você só quer abrir o arquivo em " append" mode.

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

Comentários (1)

Você poderia usar um FileStream. Isto faz todo o trabalho por si.

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

Comentários (0)