[英]How Do I Read & Write Binary Files In 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
。
FileStream fs = new FileStream(SaveFileDialog.FileName, FileMode.Open);
當您打開用於創建文件的流時,現有文件將被重寫,因此您會遇到此異常,因為文件中沒有可用數據。
讀取文件時不要使用FileMode.Create
,而應使用FileMode.Open
。 從FileMode.Create
的文檔中(重點是我的):
指定操作系統應創建一個新文件。 如果文件已經存在,它將被覆蓋。 ... FileMode.Create等效於請求如果文件不存在,則使用CreateNew; 否則,使用截斷。
顧名思義,Truncate將文件截斷為零字節長:
指定操作系統應打開現有文件。 打開文件時,應將其截斷以使其大小為零字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.