File.AppendAllText 方法 (String, String)

来源:互联网 发布:银行大劫案 知乎 编辑:程序博客网 时间:2024/06/08 11:41
此文章由机器翻译。 将光标移到文章的句子上,以查看原文。 更多信息。
译文
原文

File.AppendAllText 方法 (String, String)

.NET Framework 4.6 and 4.5
其他版本
 

打开一个文件,向其中追加指定的字符串,然后关闭该文件。如果文件不存在,此方法将创建一个文件,将指定的字符串写入文件,然后关闭该文件。

命名空间:   System.IO
程序集:  mscorlib(mscorlib.dll 中)

语法

C#
C++
F#
VB
public static void AppendAllText(string path,string contents)

参数

path

要将指定的字符串追加到的文件。

contents

要追加到文件中的字符串。

异常

ExceptionConditionArgumentException

path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。

ArgumentNullException

path 为 null

PathTooLongException

指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。

DirectoryNotFoundException

指定路径无效(例如,目录不存在或位于未映射的驱动器上)。

IOException

打开文件时发生 I/O 错误。

UnauthorizedAccessException

path 指定了一个只读文件。

- 或 -

当前平台不支持此操作。

- 或 -

path 指定了一个目录。

- 或 -

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

NotSupportedException

path 的格式无效。

SecurityException

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

备注

给定字符串和文件路径,此方法打开指定的文件,将字符串追加到文件的末尾,然后关闭该文件。文件句柄保证要关闭按照此方法,即使将引发异常。

如果不存在,但它不会创建新目录,该方法将创建该文件。因此的值 path 参数必须包含现有目录。

示例

下面的代码示例演示如何将 AppendAllText 方法将额外的文本添加到文件末尾。在此示例中,如果它尚不存在,并且文本添加到它被创建一个文件。但是,该目录的名为 temp C 必须存在才能成功完成该示例的驱动器上。

C#
VB
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);    }}

安全性

FileIOPermission

for access to write to a file or directory.Associated enumeration: FileIOPermissionAccess.Append

版本信息

Universal Windows Platform
10 后可用
.NET Framework
2.0 后可用
Silverlight
4.0 后可用
0 0
原创粉丝点击