File.AppendAllText (String, String)app
File.AppendAllText (String, String, String)less
函數說明:打開一個文件,向其中追加指定的字符串,而後關閉該文件。 若是文件不存在,此方法建立一個文件,將指定的字符串寫入文件,而後關閉該文件。函數
命名空間: System.IO
程序集: mscorlib(在 mscorlib.dll 中)ui
語法:this
public static void AppendAllText( string path, string contents )
參數說明:編碼
pathspa
類型:System.String,要將指定的字符串追加到的文件。3d
contentscode
代碼示例:orm
下面的代碼示例演示如何使用 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 參數的值必須包含現有內容。
函數說明:將指定的字符串追加到文件中,若是文件還不存在則建立該文件。
命名空間: System.IO
程序集: mscorlib(在 mscorlib.dll 中)
語法:
public static void AppendAllText( string path, string contents, Encoding encoding )
參數說明:
contents
類型:System.String,要追加到文件中的字符串。
encoding
類型:System.Text.Encoding,要使用的字符編碼。
用法:
File.AppendAllText(path, contents, Encoding)
如:File.AppendAllText(path, appendText, Encoding.UTF8);
異常 | 條件 |
---|---|
ArgumentException | path 是一個零長度字符串,僅包含空白或者包含一個或多個由 InvalidPathChars 定義的無效字符。 |
ArgumentNullException | path 爲 null。 |
PathTooLongException | 指定的路徑、文件名或者二者都超出了系統定義的最大長度。 例如,在基於 Windows 的平臺上,路徑必須小於 248 個字符,文件名必須小於 260 個字符。 |
DirectoryNotFoundException | 指定路徑無效(例如,目錄不存在或位於未映射的驅動器上)。 |
IOException | 打開文件時發生 I/O 錯誤。 |
UnauthorizedAccessException | path 指定了一個只讀文件。 - 或 - 在當前平臺上不支持此操做。 - 或 - path 指定了一個目錄。 - 或 - 調用方沒有所要求的權限。 |
FileNotFoundException | 未找到 path 中指定的文件。 |
NotSupportedException | path 的格式無效。 |
SecurityException | 調用方沒有所要求的權限。 |