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 ?
The BinaryReader class provides methods that simplify reading primitive data types from a stream. For example, you can use the ReadBoolean method to read the next byte as a Boolean value and advance the current position in the stream by one byte. The class includes read methods that support different data types.
StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.
The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor. The following table shows some of the commonly used methods of the BinaryReader class.
Both StreamReader and BinaryReader can be used to get data from binary file
Well, StreamReader
can be used to get text data from a binary representation of text.
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.
Bottom line:
StreamReader
.BinaryReader
So for example, you wouldn't try to read a JPEG file with StreamReader
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With