user2272380
user2272380

Reputation: 113

How Do I Read & Write Binary Files In C#?

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."

Here's the 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();
            }
        }
    }
}

Upvotes: 3

Views: 22209

Answers (2)

mehrandvd
mehrandvd

Reputation: 9116

You're using FileMode.Create for reading the file.

You should use FileMode.Open instead.

FileStream fs = new FileStream(SaveFileDialog.FileName, FileMode.Open);

When you open the stream for creating a file, the existing file will be rewritten, so you'll get this exception as there is no data available in the file.

Upvotes: 4

cdhowie
cdhowie

Reputation: 168948

Do not use FileMode.Create when reading the file, use FileMode.Open. From the documentation for FileMode.Create (emphasis mine):

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. ... FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.

And Truncate, as its name implies, truncates the file to be zero bytes long:

Specifies that the operating system should open an existing file. When the file is opened, it should be truncated so that its size is zero bytes.

Upvotes: 1

Related Questions