c# -- 介紹File.AppendAllText 方法


下面介紹兩個函數:

  • File.AppendAllText (String, String)

  • File.AppendAllText (String, String, String)

 

File.AppendAllText 方法 (String, String)

函數說明:打開一個文件,向其中追加指定的字符串,然后關閉該文件。 如果文件不存在,此方法創建一個文件,將指定的字符串寫入文件,然后關閉該文件。

命名空間:  System.IO
程序集:  mscorlib(在 mscorlib.dll 中)

語法:

public static void AppendAllText(
    string path,
    string contents
)

參數說明:

path

類型:System.String,要將指定的字符串追加到的文件。

contents

類型: System.String 要追加到文件中的字符串。

代碼示例:

下面的代碼示例演示如何使用 AppendAllText 方法將額外的文本添加到文件末尾。 在此示例中,該文件后,如果它已不存在,並且,文本添加到。

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);
    }
}
  • 注意點:

已知字符串和文件路徑,此方法打開指定的文件,將字符串追加到文件末尾,然后關閉文件。 即使會引發異常,也使用此方法保證文件句柄已關閉。

方法創建文件,如果不存在,則,但不創建新目錄。 因此,path 參數的值必須包含現有內容。

 

File.AppendAllText(String, String, Encoding)

函數說明:將指定的字符串追加到文件中,如果文件還不存在則創建該文件。

命名空間:  System.IO
程序集:  mscorlib(在 mscorlib.dll 中)

語法:

public static void AppendAllText(
    string path,
    string contents,
    Encoding encoding
)

 參數說明:

path
類型: System.String ,要將指定的字符串追加到的文件。

contents

類型:System.String,要追加到文件中的字符串。

encoding

類型:System.Text.Encoding,要使用的字符編碼。

用法:

File.AppendAllText(path, contents, Encoding)

如:File.AppendAllText(path, appendText, Encoding.UTF8);
 

  • 附錄:異常表
異常 條件
ArgumentException

path 是一個零長度字符串,僅包含空白或者包含一個或多個由 InvalidPathChars 定義的無效字符。

ArgumentNullException

pathnull

PathTooLongException

指定的路徑、文件名或者兩者都超出了系統定義的最大長度。 例如,在基於 Windows 的平台上,路徑必須小於 248 個字符,文件名必須小於 260 個字符。

DirectoryNotFoundException

指定路徑無效(例如,目錄不存在或位於未映射的驅動器上)。

IOException

打開文件時發生 I/O 錯誤。

UnauthorizedAccessException

path 指定了一個只讀文件。

- 或 -

在當前平台上不支持此操作。

- 或 -

path 指定了一個目錄。

- 或 -

調用方沒有所要求的權限。

FileNotFoundException

未找到 path 中指定的文件。

NotSupportedException

path 的格式無效。

SecurityException

調用方沒有所要求的權限。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM