System.IO.File.AppendText 方法

方法描述

创建一个 StreamWriter,它将 UTF-8 编码文本追加到现有文件。

语法定义(C# System.IO.File.AppendText 方法 的用法)

public static StreamWriter AppendText(
	string path
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 要向其中追加内容的文件的路径。
返回值 System.IO.StreamWriter 一个 StreamWriter,它将 UTF-8 编码文本追加到现有文件。

提示和注释

此方法等效于 StreamWriter(String, Boolean) 构造函数重载。 如果由 path 指定的文件不存在,则创建该文件。 如果该文件存在,则对 StreamWriter 的写入操作将文本追加到该文件。 允许其他线程在文件打开后读取该文件。

允许 path 参数指定相对或绝对路径信息。 相对路径信息被解释为相对于当前工作目录。 若要获取当前工作目录,请参见 GetCurrentDirectory。

path 参数不区分大小写。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.File.AppendText 方法例子

下面的示例将文本追加到文件。

using System;
using System.IO;

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.
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }	
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        using (StreamWriter sw = File.AppendText(path)) 
        {
            sw.WriteLine("This");
            sw.WriteLine("is Extra");
            sw.WriteLine("Text");
        }	

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}

异常

异常 异常描述
UnauthorizedAccessException 调用方没有所要求的权限。
ArgumentException path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
ArgumentNullException path 为 null。
PathTooLongException 指定的路径、文件名或者两者都超出了系统定义的最大长度。 例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
DirectoryNotFoundException 指定的路径无效(例如,它位于未映射的驱动器上)。
NotSupportedException path 的格式无效。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。