File.AppendText(String) Método

Definición

Crea un StreamWriter objeto que anexa texto codificado UTF-8 a un archivo existente o a un nuevo archivo si el archivo especificado no existe.

public:
 static System::IO::StreamWriter ^ AppendText(System::String ^ path);
public static System.IO.StreamWriter AppendText(string path);
static member AppendText : string -> System.IO.StreamWriter
Public Shared Function AppendText (path As String) As StreamWriter

Parámetros

path
String

Ruta de acceso al archivo al que se va a anexar.

Devoluciones

Objeto de escritura de secuencias que anexa texto codificado UTF-8 al archivo especificado o a un archivo nuevo.

Excepciones

El autor de la llamada no tiene el permiso necesario.

Versiones de .NET Framework y .NET Core anteriores a la 2.1: path es una cadena de longitud cero, solo contiene espacios en blanco o contiene uno o varios caracteres no válidos. Puede consultar caracteres no válidos mediante el método GetInvalidPathChars().

path es null.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

La ruta de acceso especificada no es válida (por ejemplo, el directorio no existe o está en una unidad no asignada).

path tiene un formato no válido.

Ejemplos

En el ejemplo siguiente se anexa texto a un archivo. El método crea un nuevo archivo si el archivo no existe. Sin embargo, el directorio denominado temp en la unidad C debe existir para que el ejemplo se complete correctamente.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }	
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine("This");
            sw.WriteLine("is Extra");
            sw.WriteLine("Text");
        }	

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
open System.IO

let path = @"c:\temp\MyTest.txt"

// This text is added only once to the file.
if File.Exists path |> not then
    // Create a file to write to.
    use sw = File.CreateText path
    sw.WriteLine "Hello"
    sw.WriteLine "And"
    sw.WriteLine "Welcome"

// This text is always added, making the file longer over time
// if it is not deleted.
do
    use sw = File.AppendText path
    sw.WriteLine "This"
    sw.WriteLine "is Extra"
    sw.WriteLine "Text"

// Open the file to read from.
do
    use sr = File.OpenText path

    let mutable s = sr.ReadLine()

    while isNull s |> not do
        printfn $"{s}"
        s <- sr.ReadLine()
Imports System.IO

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt"

    ' This text is added only once to the file. 
    If Not File.Exists(path) Then
      ' Create a file to write to.
      Using sw As StreamWriter = File.CreateText(path)
        sw.WriteLine("Hello")
        sw.WriteLine("And")
        sw.WriteLine("Welcome")
      End Using
    End If

    ' This text is always added, making the file longer over time 
    ' if it is not deleted.
    Using sw As StreamWriter = File.AppendText(path)
      sw.WriteLine("This")
      sw.WriteLine("is Extra")
      sw.WriteLine("Text")
    End Using

    ' Open the file to read from. 
    Using sr As StreamReader = File.OpenText(path)
      Do While sr.Peek() >= 0
        Console.WriteLine(sr.ReadLine())
      Loop
    End Using

  End Sub
End Class

Comentarios

Este método es equivalente a la sobrecarga del StreamWriter(String, Boolean) constructor. Si el archivo especificado por path no existe, se crea. Si el archivo existe, escriba operaciones en el StreamWriter texto anexado al archivo. Se permiten subprocesos adicionales leer el archivo mientras está abierto.

El path parámetro puede especificar información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, consulte GetCurrentDirectory.

El path parámetro no distingue mayúsculas de minúsculas.

Para obtener una lista de tareas comunes de E/S, consulte Tareas comunes de E/S.

Se aplica a

Consulte también