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#.
Use o construtor correto:
else if (File.Exists(path))
{
using(var tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}
}
Você poderia usar um FileStream. Isto faz todo o trabalho por si.