c# - 如何在 C# 中读写二进制文件?

标签 c# binary

我正在尝试用 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

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

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

关于c# - 如何在 C# 中读写二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19432468/

相关文章:

c# - WebAPI 过滤器的 ActionExecutedContext 中的异常属性为 null

c# - C#中使用Threads和ListView的问题

c# - protobuf-net - 从 .proto 生成的类 - 重复字段是否应该是只读的,没有 setter ?

c# - 尝试在 Repeater 中使用 String.Format 但出现语法错误

Java - 将 ASCII 转换为不带前导零的二进制

c++ - STL "closest"方法?

c# - INSERT INTO 语句的问题

c++ - 用于计算位或找到最右边|最左边的位的高效按位运算

java - 存储在Cpp中可读的java字节数组

c - 如何 fopen() .IMA 文件?