Search This Blog

Wednesday, November 20, 2013

Read - Write Binary to File Stream

C# > Files > Read - Write Binary

BinaryWriter : writes primitive types in binary to a stream.
BinaryReader: reads primitive data types as binary.

Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            const string fileName = "C:\\Settings.dat";
            using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
            {
                writer.Write("Verdana"); // font name
                writer.Write(10);        // font size
                writer.Write(true);      // font bold
            }
            string fontFname;
            int fontSize;
            bool fontBold;

            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                fontFname = reader.ReadString();
                fontSize = reader.ReadInt32();
                fontBold = reader.ReadBoolean();
            }
         }
    }
}