如何使用streamreader读取当前编码的byte [] [英] How to read byte[] with current encoding using streamreader

查看:329
本文介绍了如何使用streamreader读取当前编码的byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想使用C#编写在MSDN中编写的默认编码将是UTF-8,当构造函数没有编码时:

  var reader = new StreamReader(new MemoryStream (数据))。 

我也尝试过这个,但仍然以UTF-8的形式获取文件:

  var reader = new StreamReader(new MemoryStream(data),true)

我需要使用当前编码读取 byte []

解决方案

文件没有编码。一个字节数组没有编码。一个字节没有编码。编码是将字节转换为文本,反之亦然。



您在文本编辑器等中看到的实际上是程序魔术:编辑器尝试使用不同的编码, em> guesses 哪一个最有意义。这也是你使用布尔参数启用的。如果这不产生你想要的,那么这个魔法就会失败。

  var reader = new StreamReader(new MemoryStream(data) Encoding.Default); 

将使用操作系统/位置特定的默认编码。如果这还不是你想要的,那么你需要完全明确,并告诉流水手什么确切的编码要使用,例如(就像你说你不想要UTF8一样):

  var reader = new StreamReader(new MemoryStream(data),Encoding.UTF8); 


I would like to read byte[] using C# with the current encoding of the file.

As written in MSDN the default encoding will be UTF-8 when the constructor has no encoding:

var reader = new StreamReader(new MemoryStream(data)).

I have also tried this, but still get the file as UTF-8:

var reader = new StreamReader(new MemoryStream(data),true)

I need to read the byte[] with the current encoding.

解决方案

A file has no encoding. A byte array has no encoding. A byte has no encoding. Encoding is something that transforms bytes to text and vice versa.

What you see in text editors and the like is actually program magic: The editor tries out different encodings an then guesses which one makes the most sense. This is also what you enable with the boolean parameter. If this does not produce what you want, then this magic fails.

var reader = new StreamReader(new MemoryStream(data), Encoding.Default);

will use the OS/Location specific default encoding. If that is still not what you want, then you need to be completely explicit, and tell the streamreader what exact encoding to use, for example (just as an example, you said you did not want UTF8):

var reader = new StreamReader(new MemoryStream(data), Encoding.UTF8);

这篇关于如何使用streamreader读取当前编码的byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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