Leer en inglés

Compartir a través de


Procedimiento Escribir texto en un archivo

En este artículo se muestran diferentes maneras de escribir texto en un archivo para una aplicación .NET.

Las clases y los métodos siguientes normalmente se usan para escribir texto en un archivo:

Nota

En los ejemplos siguientes solo se muestra la cantidad mínima de código necesario. Normalmente, una aplicación real ofrece una comprobación de errores y un control de excepciones más exhaustivos.

Ejemplo: Escritura de texto con StreamWriter de forma sincrónica

En el ejemplo siguiente se muestra cómo usar la clase StreamWriter para escribir texto en un archivo nuevo de forma sincrónica, una línea a la vez. Como en la instrucción StreamWriter se declara el objeto using y se crea una instancia de este, se invoca el método Dispose, que automáticamente vacía y cierra el flujo.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {

        // Create a string array with the lines of text
        string[] lines = { "First line", "Second line", "Third line" };

        // Set a variable to the Documents path.
        string docPath =
          Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Write the string array to a new file named "WriteLines.txt".
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt")))
        {
            foreach (string line in lines)
                outputFile.WriteLine(line);
        }
    }
}
// The example creates a file named "WriteLines.txt" with the following contents:
// First line
// Second line
// Third line

Ejemplo: Anexión de texto con StreamWriter de forma sincrónica

En el siguiente ejemplo se muestra cómo usar la clase StreamWriter para anexar texto de forma sincrónica al archivo de texto creado en el primer ejemplo:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {

        // Set a variable to the Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Append text to an existing file named "WriteLines.txt".
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
        {
            outputFile.WriteLine("Fourth Line");
        }
    }
}
// The example adds the following line to the contents of "WriteLines.txt":
// Fourth Line

Ejemplo: Escritura de texto con StreamWriter de forma asincrónica

En el ejemplo siguiente se muestra cómo escribir texto en un archivo nuevo de forma asincrónica mediante la clase StreamWriter . Para invocar el método WriteAsync, la llamada al método debe estar dentro de un método async.

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Set a variable to the Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Write the specified text asynchronously to a new file named "WriteTextAsync.txt".
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteTextAsync.txt")))
        {
            await outputFile.WriteAsync("This is a sentence.");
        }
    }
}
// The example creates a file named "WriteTextAsync.txt" with the following contents:
// This is a sentence.

Ejemplo: Escritura y anexión de texto a la clase File

En el ejemplo siguiente se muestra cómo escribir texto en un archivo nuevo y anexar nuevas líneas de texto en el mismo archivo con la clase File . Los métodos WriteAllText y AppendAllLines abren y cierran el archivo automáticamente. Si ya existe la ruta de acceso que se proporciona al método WriteAllText, se sobrescribe el archivo.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Create a string with a line of text.
        string text = "First line" + Environment.NewLine;

        // Set a variable to the Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Write the text to a new file named "WriteFile.txt".
        File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text);

        // Create a string array with the additional lines of text
        string[] lines = { "New line 1", "New line 2" };

        // Append new lines of text to the file
        File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines);
    }
}
// The example creates a file named "WriteFile.txt" with the contents:
// First line
// And then appends the following contents:
// New line 1
// New line 2

Vea también