File.AppendAllText Método

Definição

Acrescenta a cadeia de caracteres especificada ao arquivo, criando-o, caso ele ainda não exista.

Sobrecargas

AppendAllText(String, String)

Abre um arquivo, acrescenta a cadeia de caracteres especificada no arquivo e fecha o arquivo. Se o arquivo não existir, esse método criará um arquivo, gravará a cadeia de caracteres especificada no arquivo e fechará o arquivo.

AppendAllText(String, String, Encoding)

Acrescenta a cadeia de caracteres especificada ao arquivo usando a codificação especificada, criando o arquivo, caso ele ainda não exista.

AppendAllText(String, String)

Origem:
File.cs
Origem:
File.cs
Origem:
File.cs

Abre um arquivo, acrescenta a cadeia de caracteres especificada no arquivo e fecha o arquivo. Se o arquivo não existir, esse método criará um arquivo, gravará a cadeia de caracteres especificada no arquivo e fechará o arquivo.

public:
 static void AppendAllText(System::String ^ path, System::String ^ contents);
public static void AppendAllText (string path, string contents);
public static void AppendAllText (string path, string? contents);
static member AppendAllText : string * string -> unit
Public Shared Sub AppendAllText (path As String, contents As String)

Parâmetros

path
String

O arquivo no qual a cadeia de caracteres especificada será anexada.

contents
String

A cadeia de caracteres a ser anexada ao arquivo.

Exceções

.NET Framework e versões 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. Consulte caracteres inválidos usando o método GetInvalidPathChars().

path é null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho 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).

Um erro de E/S ocorreu ao abrir o arquivo.

path especificou um arquivo somente leitura.

- ou -

Não há suporte para essa operação na plataforma atual.

- ou -

path especificou um diretório.

- ou -

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

path está em um formato inválido.

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

Exemplos

O exemplo de código a seguir demonstra o uso do AppendAllText método para adicionar texto extra ao final de um arquivo. Neste exemplo, um arquivo será criado se ele ainda não existir e o texto será adicionado a ele. No entanto, o diretório chamado temp na unidade C deve existir para que o exemplo seja concluído com êxito.

using System;
using System.IO;
using System.Text;

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.
            string createText = "Hello and Welcome" + Environment.NewLine;
            File.WriteAllText(path, createText);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText);

        // Open the file to read from.
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}
open System
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.
    let createText =
        "Hello and Welcome" + Environment.NewLine

    File.WriteAllText(path, createText)

// This text is always added, making the file longer over time
// if it is not deleted.
let appendText =
    "This is extra text" + Environment.NewLine

File.AppendAllText(path, appendText)

// Open the file to read from.
let readText = File.ReadAllText path
printfn $"{readText}"
Imports System.IO
Imports System.Text

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 File.Exists(path) = False Then

            ' Create a file to write to.
            Dim createText As String = "Hello and Welcome" + Environment.NewLine
            File.WriteAllText(path, createText)
        End If

        ' This text is always added, making the file longer over time
        ' if it is not deleted.
        Dim appendText As String = "This is extra text" + Environment.NewLine
        File.AppendAllText(path, appendText)

        ' Open the file to read from.
        Dim readText As String = File.ReadAllText(path)
        Console.WriteLine(readText)
    End Sub
End Class

Comentários

Dada uma cadeia de caracteres e um caminho de arquivo, esse método abre o arquivo especificado, acrescenta a cadeia de caracteres ao final do arquivo e fecha o arquivo. O identificador de arquivo tem a garantia de ser fechado por esse método, mesmo que exceções sejam geradas.

O método cria o arquivo se ele não existir, mas não cria novos diretórios. Portanto, o valor do parâmetro deve conter diretórios path existentes.

Aplica-se a

AppendAllText(String, String, Encoding)

Origem:
File.cs
Origem:
File.cs
Origem:
File.cs

Acrescenta a cadeia de caracteres especificada ao arquivo usando a codificação especificada, criando o arquivo, caso ele ainda não exista.

public:
 static void AppendAllText(System::String ^ path, System::String ^ contents, System::Text::Encoding ^ encoding);
public static void AppendAllText (string path, string contents, System.Text.Encoding encoding);
public static void AppendAllText (string path, string? contents, System.Text.Encoding encoding);
static member AppendAllText : string * string * System.Text.Encoding -> unit
Public Shared Sub AppendAllText (path As String, contents As String, encoding As Encoding)

Parâmetros

path
String

O arquivo no qual a cadeia de caracteres especificada será anexada.

contents
String

A cadeia de caracteres a ser anexada ao arquivo.

encoding
Encoding

A codificação de caracteres a ser usada.

Exceções

.NET Framework e versões 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. Consulte caracteres inválidos usando o método GetInvalidPathChars().

path é null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho 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).

Um erro de E/S ocorreu ao abrir o arquivo.

path especificou um arquivo somente leitura.

- ou -

Não há suporte para essa operação na plataforma atual.

- ou -

path especificou um diretório.

- ou -

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

path está em um formato inválido.

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

Exemplos

O exemplo de código a seguir demonstra o uso do AppendAllText método para adicionar texto extra ao final de um arquivo. Neste exemplo, um arquivo será criado se ele ainda não existir e o texto será adicionado a ele. No entanto, o diretório chamado temp na unidade C deve existir para que o exemplo seja concluído com êxito.

using System;
using System.IO;
using System.Text;

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.
            string createText = "Hello and Welcome" + Environment.NewLine;
            File.WriteAllText(path, createText, Encoding.UTF8);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText, Encoding.UTF8);

        // Open the file to read from.
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}
open System
open System.IO
open System.Text

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.
    let createText =
        "Hello and Welcome" + Environment.NewLine

    File.WriteAllText(path, createText, Encoding.UTF8)

// This text is always added, making the file longer over time
// if it is not deleted.
let appendText =
    "This is extra text" + Environment.NewLine

File.AppendAllText(path, appendText, Encoding.UTF8)

// Open the file to read from.
let readText = File.ReadAllText path
printfn $"{readText}"
Imports System.IO
Imports System.Text

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

        ' This text is added only once to the file.
        If File.Exists(path) = False Then

            ' Create a file to write to.
            Dim createText As String = "Hello and Welcome" + Environment.NewLine
            File.WriteAllText(path, createText, Encoding.UTF8)
        End If

        ' This text is always added, making the file longer over time
        ' if it is not deleted.
        Dim appendText As String = "This is extra text" + Environment.NewLine
        File.AppendAllText(path, appendText, Encoding.UTF8)

        ' Open the file to read from.
        Dim readText As String = File.ReadAllText(path)
        Console.WriteLine(readText)
    End Sub
End Class

Comentários

Considerando uma cadeia de caracteres e um caminho de arquivo, esse método abre o arquivo especificado, acrescenta a cadeia de caracteres ao final do arquivo usando a codificação especificada e fecha o arquivo. O identificador de arquivo tem a garantia de ser fechado por esse método, mesmo que exceções sejam geradas.

O método cria o arquivo se ele não existir, mas não cria novos diretórios. Portanto, o valor do parâmetro deve conter diretórios path existentes.

Aplica-se a