File.AppendText(String) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Cria um StreamWriter que adiciona texto codificado em UTF-8 a um ficheiro existente, ou a um novo ficheiro se o ficheiro 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 ficheiro a acrescentar.
Devoluções
Um escritor de fluxo que adiciona texto codificado em UTF-8 ao ficheiro especificado ou a um novo ficheiro.
Exceções
O interlocutor não tem a permissão necessária.
.NET Framework e .NET Core versões anteriores à 2.1: path é uma cadeia de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Pode consultar caracteres inválidos usando o GetInvalidPathChars() método.
path é null.
O caminho especificado, nome do ficheiro 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á num disco não mapeado).
path está num formato inválido.
Exemplos
O exemplo seguinte acrescenta texto a um ficheiro. O método cria um novo ficheiro se o ficheiro não existir. No entanto, o diretório nomeado temp na unidade C deve existir para que o exemplo seja concluído com sucesso.
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
Observações
Este método é equivalente à StreamWriter(String, Boolean) sobrecarga do construtor. Se o ficheiro especificado por path não existir, é criado. Se o ficheiro existir, escriva operações para StreamWriter acrescentar texto ao ficheiro. Tópicos adicionais são permitidos para ler o ficheiro enquanto este está aberto.
O path parâmetro pode especificar informação relativa ou absoluta do caminho. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Para obter o diretório de trabalho atual, veja GetCurrentDirectory.
O path parâmetro não é sensível a maiúsculas minúsculas.
Para uma lista de tarefas comuns de E/S, consulte Tarefas Comuns de E/S.