关于c#:Encoding.Default如何在.NET中运行?

How does Encoding.Default work in .NET?

我正在阅读一个文件,使用:

1
var source = File.ReadAllText(path);

字符?没有正确加载。

然后,我把它改为:

1
var source = File.ReadAllText(path, Encoding.UTF8);

什么也没有。

我决定尝试使用

1
var source = File.ReadAllText(path, Encoding.Default);

而且效果很好。然后我调试了它,并试图找出哪种编码方式起了作用,我发现它是UTF-7

我想知道的是:

是否建议使用Encoding.Default,是否能保证文件的所有字符都能正常读取?


不建议使用encoding.default。

来自msdn的报价:

Different computers can use different
encodings as the default, and the
default encoding can even change on a
single computer. Therefore, data
streamed from one computer to another
or even retrieved at different times
on the same computer might be
translated incorrectly. In addition,
the encoding returned by the Default
property uses best-fit fallback to map
unsupported characters to characters
supported by the code page. For these
two reasons, using the default
encoding is generally not recommended.
To ensure that encoded bytes are
decoded properly, your application
should use a Unicode encoding, such as
UTF8Encoding or UnicodeEncoding, with
a preamble. Another option is to use a
higher-level protocol to ensure that
the same format is used for encoding
and decoding.


默认值只保证所有的utf-7字符集都能被正确读取(整个字符集都是google)。另一方面,如果你试图读取一个没有在UTF-8模式下用UTF-8编码的文件,你会得到和你一样的损坏字符。

例如,如果文件编码为utf-16,并且以utf-16模式读取,即使该文件不包含一个特定于utf-16的字符,也可以。这一切归结为文件的编码。

你需要用相同的编码来做保存-重新打开的工作,以避免损坏。否则,尽可能多地使用UTF-7,因为它是最紧凑但"电子邮件安全"的编码,这就是为什么它在大多数.NET框架设置中是默认的。


听起来您对自动检测文件编码很感兴趣,在某种情况下,您无法控制用于保存文件的编码。StackOverflow有几个问题可以解决这个问题;一些粗略的浏览点可以确定C中字符串的编码是一个很好的编码方式。我最喜欢的答案是指向Mozilla的通用字符集检测器的C端口。


我认为UR文件是UTF-7编码的,没有别的了。访问此页面您的答案