Me gustaría crear un archivo .txt y escribir en él, y si el archivo ya existe, solo quiero añadir algunas líneas más :Cree un archivo .txt si no existe, y si agrega una nueva línea
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 conseguir siempre sobrescribe ... ¿cómo puedo evitar escribir en la misma línea (estoy usando esto en un bucle)?
Sé que es una cosa bastante simple, pero nunca he usado el método WriteLine
antes. Soy totalmente nuevo en C#.
Primera respuesta, respuesta más sencilla, respuesta más útil para mí lol. Cuando lo miré, yo estaba como: ¿Eh? solo agregar ", verdad" es suficiente? ¿Cómo es que no voy a ver eso antes? Maldición ... Me sentí como un total tonto gracias. Realmente me gustan estas buenas respuestas. –
sugerencia: si el archivo no existe, este constructor crea un nuevo archivo. –
envuélvalo en un uso (ver respuesta a continuación). –