- This program explains about how to read binary files using BinaryWriter in C# programming.
- The main advantage of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization.
- Tools needed: Button1 (Button1).
BinaryReader Class
- BinaryReader reads primitive data types as binary values in a specific encoding.
- Syntax
|
1 2 3 4 |
// Declaration [ComVisibleAttribute(true)] public class BinaryReader : IDisposable { } |
BinaryReader Constructor (Stream) – BinaryReader in C#
- It helps to initialize a new instance of the BinaryReader class based on the specified stream and using UTF-8 encoding.
- Syntax
// Declaration
public DummyClass(Stream input) {
}
|
1 2 3 |
// Declaration public DummyClass(Stream input) { } |
BinaryReader.ReadString Method – BinaryReader in C#
- It reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
- Syntax
|
1 2 3 |
// Declaration public virtual void ReadString(void As, void String) { } |
BinaryReader.Close Method – BinaryReader in C#
- It helps to close the current reader and the underlying stream.
- Syntax
|
1 2 3 |
// Declaration public virtual void Close() { } |
FileStream Class – BinaryReader in C#
- FileStream class exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
- Syntax
|
1 2 3 4 |
// Declaration [ComVisibleAttribute(true)] public class FileStream : Stream { } |
FileStream Constructor (String, FileMode) – BinaryReader in C#
- It helps to initialize a new instance of the FileStream class with the specified path and creation mode.
- Syntax
|
1 2 3 |
// Declaration public DummyClass(string path, FileMode mode) { } |
- String – A path for the file that the current FileStream object will encapsulate.
- FileMode – A constant that determines how to open or create the file.
BinaryReader in C# – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { FileStream readStream; string msg; try { readStream = new FileStream("c:\\testBinary.dat", FileMode.Open); BinaryReader readBinary = new BinaryReader(readStream); msg = readBinary.ReadString(); richTextBox1.Text = msg; readStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } |
BinaryReader in C#






