我正試圖在C#中編寫一個應用程序,該應用程序將數據寫入二進制文件,然後讀取它。問題是,當我嘗試讀取它時,該應用程序崩潰,出現錯誤「無法讀取超出流末尾」。如何在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。 –