File.AppendText(String) Метод

Определение

StreamWriter Создает текст в кодировке UTF-8 к существующему файлу или новый файл, если указанный файл не существует.

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

Параметры

path
String

Путь к файлу для добавления.

Возвращаемое значение

Модуль записи потоков, добавляющий текст в кодировке UTF-8 к указанному файлу или новому файлу.

Исключения

Вызывающий объект не имеет требуемого разрешения.

Версии .NET Framework и .NET Core старше 2.1: path представляет собой строку нулевой длины, содержит только пробелы или содержит один или несколько недопустимых символов. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars().

path равно null.

Указанный путь, имя файла или оба превышают определенную системой максимальную длину.

Указанный путь недопустим (например, каталог не существует или находится на неисправном диске).

path имеет недопустимый формат.

Примеры

В следующем примере текст добавляется в файл. Метод создает новый файл, если файл не существует. Однако каталог с именем temp на диске C должен существовать для успешного завершения примера.

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

Комментарии

Этот метод эквивалентен перегрузке конструктора StreamWriter(String, Boolean) . Если файл, указанный не path существует, он создается. Если файл существует, операции записи в StreamWriter добавляемый текст в файл. При открытии файла разрешено читать дополнительные потоки.

Параметр path может указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются как относительные к текущему рабочему каталогу. Чтобы получить текущий рабочий каталог, см. GetCurrentDirectory.

Параметр path не учитывает регистр.

Список распространенных задач ввода-вывода см. в разделе Распространенные задачи ввода-вывода.

Применяется к

См. также раздел