• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

c# -- 介绍File.AppendAllText 方法

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

下面介绍两个函数:

  • 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 要追加到文件中的字符串。

代码示例:

在此示例中,该文件后,如果它已不存在,并且,文本添加到。

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

InvalidPathChars 定义的无效字符。

ArgumentNullException

null

PathTooLongException

例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。

DirectoryNotFoundException

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

IOException

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

UnauthorizedAccessException

path 指定了一个只读文件。

- 或 -

在当前平台上不支持此操作。

- 或 -

path 指定了一个目录。

- 或 -

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

FileNotFoundException

path 中指定的文件。

NotSupportedException

path 的格式无效。

SecurityException

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Lambda表达式发布时间:2022-07-13
下一篇:
[转]C#调用C++dll发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap