如何在.NET中使用Encoding.Default? [英] How does Encoding.Default work in .NET?

查看:199
本文介绍了如何在.NET中使用Encoding.Default?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var source = File.ReadAllText(path); 

和角色©不是正确加载



然后,我将其更改为:

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

没有任何内容。



我决定尝试使用

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

它运行良好。
然后我调试它,并尝试找到哪个Encoding做了诀窍,我发现它是 UTF-7



我想知道的是:



建议使用 Encoding.Default 并且它可以保证文件的所有字符都将被读取没有问题吗?

解决方案

Encoding.Default将仅保证所有UTF -7字符集将被正确读取(google为整个集合)。另一方面,如果您尝试以UTF-8模式读取未以UTF-8编码的文件,那么您将收到像您一样损坏的字符。



例如,如果文件被编码为UTF-16,并且如果您以UTF-16模式读取文件,即使该文件不包含单个UTF-16特定字符,您也可以使用。所有这些都归结为文件的编码。



您需要使用相同的编码进行保存重新打开的东西,以防止损坏。否则,尝试尽可能多地使用UTF-7,因为它是最紧凑的电子邮件安全编码可能,这就是为什么在大多数.NET框架设置中是默认的。


I'm reading a file using:

var source = File.ReadAllText(path);

and the character © wasn't being loaded correctly.

Then, I changed it to:

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

and nothing.

I decided to try using

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

and it worked perfectly. Then I debugged it and tried to find which Encoding did the trick, and I found that it was UTF-7.

What I want to know is:

Is it recommended to use Encoding.Default, and can it guarantee all the characters of the file will be read without problems?

解决方案

Encoding.Default will only guarantee that all UTF-7 character sets will be read correctly (google for the whole set). On the other hand, if you try to read a file not encoded with UTF-8 in the UTF-8 mode, you'll get corrupted characters like you did.

For instance if the file is encoded UTF-16 and if you read it in UTF-16 mode, you'll be fine even if the file does not contain a single UTF-16 specific character. It all boils down to the file's encoding.

You'll need to do the save - reopen stuff with the same encoding to be safe from corruptions. Otherwise, try to use UTF-7 as much as you can since it is the most compact yet 'email safe' encoding possible, which is why it is default in most .NET framework setups.

这篇关于如何在.NET中使用Encoding.Default?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆