c# - 编码.UTF8 默认

标签 c# .net encoding utf-8 character-encoding

我刚刚用StreamWriter写了一个文件,发现必须显式设置编码为Encoding.UTF8,它才能写汉字,否则就出来了作为胡言乱语。

我有两个问题:

  1. 如何将默认编码设置为 Encoding.UTF8,这样我就不必总是明确地设置它?
  2. 为什么 Encoding.UTF8Encoding.Unicode 不是 StreamWriter 的默认值,因为 .NET 字符串默认为 UTF-16?<

最佳答案

Why is Encoding.UTF8 or Encoding.Unicode not default for StreamWriter

UTF8 实际上 StreamWriter 的默认值。来自 StreamWriter(string) 构造函数的 MSDN 文档:

This constructor creates a StreamWriter with UTF-8 encoding without a Byte-Order Mark (BOM), so its GetPreamble method returns an empty byte array. The default UTF-8 encoding for this constructor throws an exception on invalid bytes. This behavior is different from the behavior provided by the encoding object in the Encoding.UTF8 property. To specify a BOM and determine whether an exception is thrown on invalid bytes, use a constructor that accepts an encoding object as a parameter, such as StreamWriter(String, Boolean, Encoding).

因此,真正的问题在于读取文件的程序,它需要 BOM 来可靠地解码文件中的文本。这并非完全不寻常。

遗憾的是,StreamWriter 类必须遵循 Unicode 标准,该标准规定 BOM 是可选很多钦佩 Unicode 联盟所做的事情,坦率地说,这个决定不是其中之一。

您必须适应该程序和 Unicode 标准,通过使用采用 Encoding 参数并指定 Encoding.UTF8 的 StreamWriter 构造函数轻松解决您的问题

关于c# - 编码.UTF8 默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21602915/

相关文章:

C# 使用 DateTime.TryParseExact() 多种格式解析 DateTime

c# - 好的 lambda 表达式或减少每个循环的更好方法

java - 使用java邮件API发送电子邮件时出现编码问题

c - Windows : How to build X264. lib 而不是 .dll

java - 在 PHP 中加密时间戳并在 Java 中解密

c# - DataTable 使用带逗号的 Datacolumn Name 排序

c# - 复杂的 Linq C# 查询

c# - 根据角色确定用户是否有权访问给定的 Controller 操作

c# - 非托管库中的堆栈溢出导致 .NET 应用程序崩溃

c# - 如何让 FileHelpers 在定义的列之后忽略列? (即忽略最后的列)