加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – File.AppendAllText默认编码

发布时间:2020-12-15 08:12:00 所属栏目:百科 来源:网络整理
导读:现有代码调用File.AppendAllText(文件名,文本)重载以将文本保存到文件. 我需要能够在不破坏向后兼容性的情况下指定编码.如果我要使用File.AppendAllText(文件名,文本,编码)重载哪个编码我需要指定以确保文件以完全相同的方式创建? 解决方法 AppendAllText()
现有代码调用File.AppendAllText(文件名,文本)重载以将文本保存到文件.

我需要能够在不破坏向后兼容性的情况下指定编码.如果我要使用File.AppendAllText(文件名,文本,编码)重载哪个编码我需要指定以确保文件以完全相同的方式创建?

解决方法

AppendAllText()的两个参数重载最终使用不带BOM的UTF-8编码调用内部方法File.InternalAppendAllText():
[SecuritySafeCritical]
public static void AppendAllText(string path,string contents)
{
    if (path == null) {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0) {
        throw new ArgumentException(
            Environment.GetResourceString("Argument_EmptyPath"));
    }
    File.InternalAppendAllText(path,contents,StreamWriter.UTF8NoBOM);
}

因此,你可以写:

using System.IO;
using System.Text;

File.AppendAllText(filename,text,new UTF8Encoding(false,true));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读