title: How Do I Read & Write Binary Files In C#?
body: <p>I'm trying to write an app in C# that will write data to a binary file and then read it. The problem is that when I try to read it, the app crashes with the error "Unable to read beyond the end of the stream."</p>
  
  <p>Here's the code:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Windows.Forms;
  using System.IO;
  
  namespace Read_And_Write_To_Binary
  {
      public partial class Form1 : Form
      {
          public Form1()
          {
              InitializeComponent();
          }
  
          private void btnSave_Click(object sender, EventArgs e)
          {
              SaveFileDialog SaveFileDialog = new SaveFileDialog();
              SaveFileDialog.Title = "Save As...";
              SaveFileDialog.Filter = "Binary File (*.bin)|*.bin";
              SaveFileDialog.InitialDirectory = @"C:\";
              if (SaveFileDialog.ShowDialog() == DialogResult.OK)
              {
                  FileStream fs = new FileStream(SaveFileDialog.FileName, FileMode.Create);
                  // Create the writer for data.
                  BinaryWriter bw = new BinaryWriter(fs);
  
                  string Name = Convert.ToString(txtName.Text);
                  int Age = Convert.ToInt32(txtAge.Text);
                  bw.Write(Name);
                  bw.Write(Age);
  
                  fs.Close();
                  bw.Close();
              }
           }
  
          private void btnOpen_Click(object sender, EventArgs e)
          {
              OpenFileDialog OpenFileDialog = new OpenFileDialog();
              OpenFileDialog.Title = "Open File...";
              OpenFileDialog.Filter = "Binary File (*.bin)|*.bin";
              OpenFileDialog.InitialDirectory = @"C:\";
              if (OpenFileDialog.ShowDialog() == DialogResult.OK)
              {
                  FileStream fs = new FileStream(OpenFileDialog.FileName, FileMode.Create);
                  BinaryReader br = new BinaryReader(fs);
  
                  lblName.Text = br.ReadString();
                  lblAge.Text = br.ReadInt32();
  
                  fs.Close();
                  br.Close();
              }
          }
      }
  }
  </code></pre>