C#文件流二进制文件的读写

目录

一、BinaryWriter类

二、BinaryReader类

三、示例

1.源码

2.生成效果


二进制文件的写入与读取主要是通过BinaryWriter类和BinaryReader类来实现的。

一、BinaryWriter类

BinaryWriter类以二进制形式将基元类型写入流,并支持用特定的编码写入字符串,其常用方法及说明:

|-------------|------------------------|
| 方 法 | 说 明 |
| Close | 关闭当前的BinaryWriter类和基础流 |
| Seek | 设置当前流中的位置 |
| Write | 将值写入当前流 |

二、BinaryReader类

BinaryReader用特定的编码将基元数据类型读作二进制值,其常用方法及说明:

|-------------|-----------------------------------------------------------------|
| 方 法 | 说 明 |
| Close | 关闭当前阅读器及基础流 |
| PeekChar | 返回下一个可用的字符,并且不提升字节或字符的位置 |
| Read | 从基础流中读取字符,并提升流的当前位置 |
| ReadBoolean | 从当前流中读取Boolean值,并使该流的当前位置提升一个字节 |
| ReadByte | 从当前流中读取下一个字节,并使流的当前位置提升一个字节 |
| ReadBytes | 从当前流中将count个字节读入字节数组,并使当前位置提升count个字节 |
| ReadChar | 从当前流中读取下一个字符,并根据所使用的Encoding和从流中读取的特定字符,提升流的当前位置 |
| ReadChars | 从当前流中读取count个字符,以字符数组的形式返回数据,并根据所使用的Encoding和从流中读取 的特定字符,提升当前位置 |
| ReadInt32 | 从当前流中读取4个字节有符号整数,并使流的当前位置提升4个字节 |
| ReadString | 从当前流中读取一个字符串。字符串有长度前缀, 一次将7位编码为整数 |

三、示例

1.源码

cs 复制代码
//文件流的二进制读写
//Windows窗体应用.NET8.0,不用设计器
namespace _08
{
    public partial class Form1 : Form
    {
        private Button? button1;
        private Button? button2;
        private TextBox? textBox1;
        private OpenFileDialog? openFileDialog1;
        private SaveFileDialog? saveFileDialog1;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }

        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对象
                    using (FileStream? myStream = new(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {                      
                        new BinaryWriter(myStream).Write(textBox1.Text); //内联临时变量二进制写入流对象                    
                        new BinaryWriter(myStream).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对象
                using FileStream? myStream = new(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                if (new BinaryReader(myStream).PeekChar() != -1)   //内联临时变量二进制写入流
                {                   
                    textBox1.Text = Convert.ToString(
                        new BinaryReader(myStream).ReadString());  //以二进制方式读取文件
                }               
                new BinaryReader(myStream).Close();                //关闭当前二进制读取流               
                myStream.Close();                                  //关闭当前文件流
            }
        }

        private void Form1_Load(object? sender, EventArgs e)
        {
            // textBox1
            textBox1 = new TextBox
            {
                Location = new Point(12, 29),
                Multiline = true,
                Name = "textBox1",
                Size = new Size(270, 111)
            };
            // label1
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 9),
                Text = "文件内容:"
            };
            // button1
            button1 = new Button
            {
                Location = new Point(66, 146),
                Name = "button1",
                Size = new Size(75, 23),
                Text = "写入",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // button2
            button2 = new Button
            {
                Location = new Point(147, 146),
                Name = "button2",
                Size = new Size(75, 23),
                Text = "读取",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // openFileDialog1
            openFileDialog1 = new OpenFileDialog
            {
                FileName = "openFileDialog1"
            };
            //saveFileDialog1
            saveFileDialog1 = new SaveFileDialog();
            //Form1
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(295, 180);
            StartPosition = FormStartPosition.CenterScreen;
            Controls.Add(label1);
            Controls.Add(textBox1);
            Controls.Add(button2);
            Controls.Add(button1);
        }    
    }
}

2.生成效果

操作过程:因为我先前在当前目录下已经存过一个二进制文件了,所以:生成→ 读取→ 浏览到当前目录,并选择目录下的二进制文件,打开显示在文本框里。→ 编辑打开的文件,存储,可以另存为,也可以覆盖原文件。→ 再打开文件。

相关推荐
mudtools1 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下6 小时前
最终的信号类
开发语言·c++·算法
echoarts7 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix7 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz7 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题8 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说8 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔8 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号9 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_9 小时前
QT(4)
开发语言·汇编·c++·qt·算法