【问题标题】:How Do I Read & Write Binary Files In C#?如何在 C# 中读写二进制文件?
【发布时间】:2013-10-17 16:39:31
【问题描述】:

我正在尝试用 C# 编写一个应用程序,它将数据写入二进制文件然后读取它。问题是当我尝试读取它时,应用程序崩溃并出现错误“无法读取超出流的末尾。”

代码如下:

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();
            }
        }
    }
}

【问题讨论】:

  • 不要在读取文件的代码中使用 FileMode.Create。那会破坏它。你当然想要 FileMode.Open。​​

标签: c# binary


【解决方案1】:

您正在使用FileMode.Create 读取文件。

您应该改用FileMode.Open

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

当您打开用于创建文件的流时,现有文件将被重写,因此您将收到此异常,因为文件中没有可用的数据。

【讨论】:

    【解决方案2】:

    读取文件时不要使用FileMode.Create,使用FileMode.Open。从the documentationFileMode.Create(强调我的):

    指定操作系统应该创建一个新文件。 如果文件已经存在,则覆盖。 ... FileMode.Create相当于请求如果文件不存在,使用CreateNew;否则,使用截断。

    而Truncate,顾名思义,就是将文件截断为零字节长:

    指定操作系统应打开现有文件。打开文件时,应将其截断,使其大小为零字节。

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2019-09-18
      • 2020-09-03
      • 1970-01-01
      • 2013-07-10
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多