Añadir líneas a un archivo usando un StreamWriter


Quiero añadir líneas a mi archivo. Estoy usando un StreamWriter:

StreamWriter file2 = new StreamWriter(@"c:\file.txt");
file2.WriteLine(someString);
file2.Close();

La salida de mi archivo debe ser varias cadenas debajo de la otra, pero solo tengo una fila, que se sobrescribe cada vez que corro este código.

¿Hay alguna forma de permitir que el StreamWriter se agregue a un archivo existente?

Author: CodeCaster, 2011-09-05

10 answers

Usa esto en su lugar:

new StreamWriter("c:\\file.txt", true);

Con esta sobrecarga del constructor StreamWriter eliges si anexas el archivo, o lo sobrescribes.

C # 4 y superior ofrece la siguiente sintaxis, que algunos encuentran más legible:

new StreamWriter("c:\\file.txt", append: true);
 233
Author: Øyvind Bråthen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-19 16:12:58
 using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
 using (StreamWriter sw = new StreamWriter(fs))
 {
    sw.WriteLine(something);
 }
 133
Author: Andrey Taptunov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-05 10:54:11

Asumo que estás ejecutando todo del código anterior cada vez que escribes algo en el archivo. Cada vez que se abre la secuencia para el archivo, su puntero de búsqueda se coloca al principio para que todas las escrituras terminen sobrescribiendo lo que estaba allí antes.

Puede resolver el problema de dos maneras: ya sea con la conveniente

file2 = new StreamWriter("c:/file.txt", true);

O reposicionando explícitamente el puntero de flujo usted mismo:

file2 = new StreamWriter("c:/file.txt");
file2.BaseStream.Seek(0, SeekOrigin.End);
 10
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-05 09:37:50

Prueba esto:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();
 9
Author: Marco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-05 09:37:02

Sustitúyase esto:

StreamWriter file2 = new StreamWriter("c:/file.txt");

Con esto:

StreamWriter file2 = new StreamWriter("c:/file.txt", true);

true indica que añade texto.

 7
Author: Waqas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-07 18:12:46

Use este StreamWriter constructor con el 2do parámetro - true.

 5
Author: Kirill Polishchuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-05 09:49:17

Otra opción es usar System. IO. File. AppendText

Esto es equivalente a las sobrecargas de StreamWriter que otros han dado.

También Archivo.AppendAllText puede proporcionar una interfaz un poco más fácil sin tener que preocuparse por abrir y cerrar la transmisión. Aunque es posible que deba preocuparse por poner sus propios frenos de línea. :)

 5
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-18 08:42:43

En realidad solo la respuesta de Jon (Sep 5 '11 a las 9:37) con BaseStream.Seek trabajó para mi caso. Gracias Jon! Necesitaba añadir líneas a un archivo txt zip archivado.

using (FileStream zipFS = new FileStream(@"c:\Temp\SFImport\test.zip",FileMode.OpenOrCreate))
{
    using (ZipArchive arch = new ZipArchive(zipFS,ZipArchiveMode.Update))
    {
        ZipArchiveEntry entry = arch.GetEntry("testfile.txt");
        if (entry == null)
        {
            entry = arch.CreateEntry("testfile.txt");
        }
        using (StreamWriter sw = new StreamWriter(entry.Open()))
        {
            sw.BaseStream.Seek(0,SeekOrigin.End);
            sw.WriteLine("text content");
        }
    }
}
 4
Author: Veroslav Olic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-12 07:49:36

Una forma más simple es usar el File.AppendText que agrega texto codificado UTF-8 a un archivo existente, o a un nuevo archivo si el archivo especificado no existe y devuelve un System.IO.StreamWriter

using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{                                                
    sw.WriteLine("this is a log");
}
 2
Author: Vinod Srivastav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 12:28:53

Reemplace esta línea:

StreamWriter sw = new StreamWriter("c:/file.txt");

Con este código:

StreamWriter sw = File.AppendText("c:/file.txt");

Y luego escribe tu línea en el archivo de texto así:

sw.WriteLine("text content");
 1
Author: Shahaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-13 13:03:26