Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader vs 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 ?

like image 334
Royi Namir Avatar asked Apr 27 '12 15:04

Royi Namir


People also ask

What is the use of BinaryReader?

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.

What is StreamReader C#?

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.

What is a binary reader in Visual Basic programming?

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.


1 Answers

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:

  • 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

So for example, you wouldn't try to read a JPEG file with StreamReader.

like image 60
Jon Skeet Avatar answered Sep 24 '22 12:09

Jon Skeet