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

调用方没有所要求的权限。

 

posted @ 2013-12-20 18:18  lmei  阅读(13919)  评论(0编辑  收藏  举报