File.AppendText(String) Método

Definición

Crea un StreamWriter 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 del archivo al que se va a anexar.

Devoluciones

StreamWriter

Un escritor de secuencias que anexa el texto con codificación UTF-8 al archivo especificado o a un nuevo archivo.

Excepciones

El llamador no dispone del permiso requerido.

Versiones de .NET Framework y .NET Core anteriores a 2.1: path es una cadena de longitud cero, contiene solo espacios en blanco o contiene uno o varios caracteres no válidos. Puede consultar los caracteres no válidos con 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 está en 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 namespace System;
using namespace System::IO;

int 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.
      StreamWriter^ sw = File::CreateText( path );
      try
      {
         sw->WriteLine( "Hello" );
         sw->WriteLine( "And" );
         sw->WriteLine( "Welcome" );
      }
      finally
      {
         if ( sw )
            delete (IDisposable^)sw;
      }
   }
   
   // This text is always added, making the file longer over time
   // if it is not deleted.
   StreamWriter^ sw = File::AppendText( path );
   try
   {
      sw->WriteLine( "This" );
      sw->WriteLine( "is Extra" );
      sw->WriteLine( "Text" );
   }
   finally
   {
      if ( sw )
         delete (IDisposable^)sw;
   }
   
   // Open the file to read from.
   StreamReader^ sr = File::OpenText( path );
   try
   {
      String^ s = "";
      while ( s = sr->ReadLine() )
      {
         Console::WriteLine( s );
      }
   }
   finally
   {
      if ( sr )
         delete (IDisposable^)sr;
   }
}
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);
            }
        }
    }
}
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 para 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 las tareas de E/S comunes, consulte Tareas de E/S comunes.

Se aplica a

Consulte también