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#.
149
3
Utilice el constructor correcto:
Sólo quieres abrir el archivo en modo "append".
http://msdn.microsoft.com/en-us/library/3zc0w663.aspx
Puedes utilizar un FileStream. Esto hace todo el trabajo por ti.
http://www.csharp-examples.net/filestream-open-file/