File.AppendText(String) Método

Definição

Cria um StreamWriter que acrescenta texto codificado em UTF-8 a um arquivo existente ou a um novo arquivo se o arquivo especificado não existir.

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

O caminho para o arquivo ao qual acrescentar.

Retornos

Um gravador de fluxo que acrescenta texto codificado em UTF-8 ao arquivo especificado ou a um novo arquivo.

Exceções

O chamador não tem a permissão necessária.

Versões do .NET Framework e do .NET Core anteriores à 2.1: path é uma cadeia de caracteres de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Você pode consultar caracteres inválidos usando o GetInvalidPathChars() método.

path é null.

O caminho especificado, o nome do arquivo ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado é inválido (por exemplo, o diretório não existe ou está em uma unidade não mapeada).

path está em um formato inválido.

Exemplos

O exemplo a seguir acrescenta texto a um arquivo. O método criará um novo arquivo se o arquivo não existir. No entanto, o diretório nomeado temp na unidade C deve existir para que o exemplo seja concluído com êxito.

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

Comentários

Esse método é equivalente à sobrecarga do StreamWriter(String, Boolean) construtor. Se o arquivo especificado por path não existir, ele será criado. Se o arquivo existir, escreva operações no StreamWriter texto de acréscimo ao arquivo. Threads adicionais têm permissão para ler o arquivo enquanto ele está aberto.

O path parâmetro tem permissão para especificar informações de caminho relativas ou absolutas. As informações de caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.

O path parâmetro não diferencia maiúsculas de minúsculas.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Aplica-se a

Confira também