我正在尝试用 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();
}
}
}
}