Compartir a través de


Cómo: Escribir en un archivo de texto (Guía de programación de C#)

En estos ejemplos se muestran varias formas de escribir texto en un archivo. En los dos primeros ejemplos se utilizan métodos estáticos en la clase File para escribir una matriz de cadenas completa o una cadena completa en un archivo de texto. En el ejemplo 3 se muestra cómo agregar texto a un archivo cuando es necesario procesar cada línea individualmente antes de escribir en el archivo. En los ejemplos del 1 al 3 se sobrescribe todo el contenido existente en el archivo. En el ejemplo 4 se muestra cómo anexar texto a un archivo existente.

Ejemplo

class WriteTextFile
{
    static void Main()
    {

        // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
        // You can modify the path if necessary. 

        // Example #1: Write an array of strings to a file. 
        // Create a string array that consists of three lines. 
        string[] lines = { "First line", "Second line", "Third line" };
        // WriteAllLines creates a file, writes a collection of strings to the file, 
        // and then closes the file.
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);


        // Example #2: Write one string to a text file. 
        string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";
        // WriteAllText creates a file, writes the specified string to the file, 
        // and then closes the file.
        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        // Example #3: Write only some strings in an array to a file. 
        // The using statement automatically closes the stream and calls  
        // IDisposable.Dispose on the stream object. 
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file. 
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }

        // Example #4: Append new text to an existing file. 
        // The using statement automatically closes the stream and calls  
        // IDisposable.Dispose on the stream object. 
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
        {
            file.WriteLine("Fourth line");
        }
    }
}
 //Output (to WriteLines.txt): 
 //   First line 
 //   Second line 
 //   Third line 

 //Output (to WriteText.txt): 
 //   A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type. 

 //Output to WriteLines2.txt after Example #3: 
 //   First line 
 //   Third line 

 //Output to WriteLines2.txt after Example #4: 
 //   First line 
 //   Third line 
 //   Fourth line

En todos estos ejemplos se escriben literales de cadena en los archivos, pero es más conveniente utilizar el método Format, que tiene muchos controles para escribir diferentes tipos de valores alineados a la derecha o a la izquierda en un campo, con o sin relleno, etc.

Compilar el código

Copie el código en una aplicación de consola.

Reemplace "c:\testdir" por un nombre de carpeta real del equipo o cree una carpeta con ese nombre.

Programación eficaz

Las condiciones siguientes pueden provocar una excepción:

  • El archivo ya existe y es de solo lectura.

  • Puede que el nombre de ruta de acceso sea demasiado largo.

  • Es posible que el disco esté lleno.

Vea también

Conceptos

Guía de programación de C#

Otros recursos

Registro y sistema de archivos (Guía de programación de C#)

Ejemplo: guardar una colección en el almacenamiento para la aplicación