System.IO.File.AppendAllText()
是 C# 中用于向文件末尾追加内容的便捷方法
public static void AppendAllText(string path, string contents);
public static void AppendAllText(string path, string contents, Encoding encoding);
2. 核心功能
-
追加内容:将文本写入文件末尾(保留原有内容)。
-
自动创建文件:如果文件不存在,会自动创建。
-
简化操作:内部自动处理文件打开、写入和关闭。
3. 参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
path | string | 是 | 目标文件路径(绝对或相对路径) |
contents | string | 是 | 要追加的文本内容 |
encoding | Encoding | 否 | 文本编码(默认UTF-8 ,若需其他编码如Encoding.ASCII 需显式指定) |
用法如下:
string filePath = "logs.txt";
string newContent = "This will be appended to the file.\n";
File.AppendAllText(filePath, newContent);