當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# File.AppendAllText(String, String)用法及代碼示例

File.AppendAllText(String, String)是一個內置的 File 類方法,用於將指定的字符串附加到給定的文件,如果該文件存在,則創建一個新文件,然後完成附加。它還關閉文件。
用法:

public static void AppendAllText (string path, string contents);

參數:此函數接受兩個參數,如下所示:

  • path: This is the file where given contents are going to be appended.
  • contents: This is the specified contents which is to be appended to the file.

異常:

  • ArgumentException:路徑是一個長度為零的字符串,隻包含空格,或者一個或多個由 InvalidPathChars 定義的無效字符。
  • ArgumentNullException:路徑為空。
  • PathTooLongException:給定的路徑、文件名或兩者都超過了 system-defined 的最大長度。
  • DirectoryNotFoundException:給定的路徑無效,即目錄不存在或位於未映射的驅動器上。
  • IOException:打開文件時發生I /O錯誤。
  • UnauthorizedAccessException:該路徑指定了一個隻讀文件。或者當前平台不支持此操作。或路徑指定目錄。或調用者沒有所需的權限。
  • NotSupportedException:路徑格式無效。
  • SecurityException:調用者沒有所需的權限。

下麵是說明 File.AppendAllText(String, String) 方法的程序。
程序1:在運行以下代碼之前,會創建一個文件,其中包含如下所示的一些內容:

file.txt

C#


// C# program to illustrate the usage
// of File.AppendAllText() method
// Using System, System.IO,
// and System.Text namespaces
using System;
using System.IO;
using System.Text;
class GFG {
    // Main() method
    public static void Main()
    {
        // Creating a file
        string myfile = @"file.txt";
        // Adding extra texts
        string appendText = "is a CS portal." + Environment.NewLine;
        File.AppendAllText(myfile, appendText);
        // Opening the file to read from.
        string readText = File.ReadAllText(myfile);
        Console.WriteLine(readText);
    }
}

執行:

mcs -out:main.exe main.cs
mono main.exe
GeeksforGeeks
is a CS portal.

運行上述代碼後,顯示如上輸出,文件內容如下所示:

file.txt

程序2:最初沒有創建文件,但下麵的代碼本身會創建一個新文件並附加指定的內容。

C#


// C# program to illustrate the usage
// of File.AppendAllText() method
// Using System, System.IO,
// and System.Text namespaces
using System;
using System.IO;
using System.Text;
class GFG {
    // Main() method
    public static void Main()
    {
        // Creating a file
        string myfile = @"file.txt";
        // Checking the existence of file
        if (!File.Exists(myfile)) {
            // Creating a file with below content
            string createText = "GFG" + Environment.NewLine;
            File.WriteAllText(myfile, createText);
        }
        // Adding extra contents
        string appendText = "is a CS portal." + Environment.NewLine;
        File.AppendAllText(myfile, appendText);
        // Opening the file to read from.
        string readText = File.ReadAllText(myfile);
        Console.WriteLine(readText);
    }
}

執行:

mcs -out:main.exe main.cs
mono main.exe
GFG
is a CS portal.

運行上述代碼後,顯示了上麵的輸出並創建了一個新文件,如下所示:

file.txt


相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.AppendAllText(String, String) Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。