StreamReader与BinaryReader? [英] StreamReader vs BinaryReader?
问题描述
StreamReader
和 BinaryReader
均可用于从二进制文件中获取数据(例如)
Both StreamReader
and BinaryReader
can be used to get data from binary file ( for example )
BinaryReader:
using (FileStream fs = File.Open(@"c:\1.bin",FileMode.Open))
{
byte[] data = new BinaryReader(fs).ReadBytes((int)fs.Length);
Encoding.getstring....
}
StreamReader:
using (FileStream fs = File.Open(@"c:\1.bin",FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs,Encoding.UTF8))
{
var myString=sr.ReadToEnd();
}
}
有什么区别,何时应使用?
What is the difference and when should I use which ?
推荐答案
StreamReader和BinaryReader均可用于从二进制文件中获取数据
Both StreamReader and BinaryReader can be used to get data from binary file
嗯, StreamReader
可用于从文本的二进制表示形式获取文本数据。
Well, StreamReader
can be used to get text data from a binary representation of text.
BinaryReader
可用于获取任意二进制数据。如果某些二进制数据恰好是文本的表示形式,那就很好-但这不是必须的。
BinaryReader
can be used to get arbitrary binary data. If some of that binary data happens to be a representation of text, that's fine - but it doesn't have to be.
底线:
- 如果整个数据都是文本数据的简单二进制编码,请使用
StreamReader
。 - 如果您基本上已经获得了 binary 数据,而文本中可能恰好有 some 部分,请使用
BinaryReader
- If the entirety of your data is a straightforward binary encoding of text data, use
StreamReader
. - If you've fundamentally got binary data which may happen to have some portions in text, use
BinaryReader
例如,您不会尝试使用以下命令读取JPEG文件 StreamReader
。
So for example, you wouldn't try to read a JPEG file with StreamReader
.
这篇关于StreamReader与BinaryReader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!