- This program explains about how to write 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).
BinaryWriter Class
- Helps to write primitive types in binary to a stream and supports writing strings in a specific encoding.
- Syntax for BinaryWriter
|
1 2 3 4 5 |
// Declaration [SerializableAttribute()] [ComVisibleAttribute(true)] public class BinaryWriter : IDisposable { } |
BinaryWriter Constructor (Stream) – BinaryWriter in C#
- It initializes a new instance of the BinaryWriter class based on the specified stream and using UTF-8 encoding.
- Syntax
|
1 2 3 |
// Declaration public DummyClass(Stream output) { } |
BinaryWriter.Write Method (String) – BinaryWriter in C#
- Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
- Syntax
|
1 2 3 |
// Declaration public virtual void Write(string value) { } |
FileStream Class – BinaryWriter 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) – BinaryWriter 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.
BinaryWriter 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 |
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 writeStream; try { writeStream = new FileStream("c:\\testBinary.dat", FileMode.Create); BinaryWriter writeBinay = new BinaryWriter(writeStream); writeBinay.Write(richTextBox1.Text); writeBinay.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } |
BinaryWriter in C#






