二进制文件需要通过FileStream实例化的对象来实例化二进制写入流对象,在读取的时候则需要转换为二进制的内容
代码
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 WindowsFormsApp14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入写入内容!");
}
else
{
saveFileDialog1.Filter = "二进制文件(*.bmp)|*.bmp";
//设置文件保存格式
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
////如果保存对话框打开了
FileStream f = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate,
FileAccess.ReadWrite);
//实例化FileStream对象,saveFileDialog1.FileName为用户输入的文件名
BinaryWriter w = new BinaryWriter(f);
//实例化BinaryWriter对象
w.Write(textBox1.Text);
//写入内容
w.Close();//关闭二进制写入流
f.Close();//关闭文件流
textBox1.Clear();
}
}
}
private void btnRead_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "二进制文件(*.bmp)|*.bmp";
//设置文件读取格式
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
////如果保存对话框打开了
FileStream f = new FileStream(saveFileDialog1.FileName, FileMode.Open,
FileAccess.Read);
//实例化FileStream对象,saveFileDialog1.FileName为用户输入的文件名
BinaryReader r = new BinaryReader(f);
//实例化BinaryReader对象
if (r.BaseStream.Position < r.BaseStream.Length)
{
//判断不超出流的结尾
textBox1.Text = Convert.ToString(r.ReadUInt32());
}
r.Close();//关闭二进制读取流
f.Close();//关闭文件流
}
}
}
}