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 | 调用方没有所要求的权限。 |