二进制文件读写
二进制文件读写主要通过BinaryWrite和BinaryReader类来实现的。
创建一个windows应用窗体,添加一个SaveFileDialog控件,Open
FileDialog控件,Text Box控件,两个Button控件。
需要添加的指令:using System.IO;
窗体设计部分:
代码:
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 二进制文件读写
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("要写的文本不能为空");
}
else
{
saveFileDialog1.Filter = "二进制文件(*.dat)|*.dat"; //设置保存文件格式
if (saveFileDialog1.ShowDialog() == DialogResult.OK) //判断是否选择文件
{
//使用另存为
FileStream myStream = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);//写入文件
BinaryWriter myWriter = new BinaryWriter(myStream);
myWriter.Write(textBox1.Text);
myWriter.Close();
myStream.Close();
textBox1.Text = string.Empty;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "二进制(*.dat)|*.dat";
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
textBox1.Text = string.Empty;
FileStream myStream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);//读取数据
BinaryReader myReader = new BinaryReader(myStream);
if(myReader.PeekChar()!=-1)
{
textBox1.Text = Convert.ToString(myReader.ReadInt32());
}
myReader.Close();
myStream.Close();
}
}
}
}
运行结果:
存储文本:
读取文本
谢谢!