3

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();
            }
        }
    }
}
1
  • 2
    Don't use FileMode.Create in the code that reads the file. That destroys it. You want FileMode.Open of course. Commented Oct 17, 2013 at 16:42

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.