C#窗体应用(一)Bin文件读取

C#窗体应用(一)bin文件读取

应用界面

界面如下图,添加一个button、两个textbox、和一个OpenFileDialog控件。
在这里插入图片描述

原代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace open_bin
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void button1_Click(object sender, EventArgs e)
        {         
            openFileDialog1.Filter = "*.bin|*.BIN";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox2.Text = openFileDialog1.FileName;               
                int file_len;//bin文件长度
                int addr = 0;//地址从0x00000000开始
                int count = 0;//换行显示计数
                byte[] binchar = new byte[] { };

                FileStream Myfile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                BinaryReader binreader = new BinaryReader(Myfile);

                file_len = (int)Myfile.Length;//获取bin文件长度

                StringBuilder str = new StringBuilder();

                binchar = binreader.ReadBytes(file_len);

                foreach (byte j in binchar)
                {
                    if (count % 16 == 0)
                    {
                        count = 0;
                        if (addr > 0)
                            str.Append("\r\n");
                        str.Append(addr.ToString("x8") + "      ");
                        addr++;
                    }

                    str.Append(j.ToString("X2") + " ");
                    if (count == 8)
                        str.Append("  ");
                    count++;
                }
                textBox1.Text = str.ToString();
                binreader.Close();
            }            
        }
    }
}

效果展示

在这里插入图片描述

程序下载地址

bin文件读取器


版权声明:本文为qq_29559457原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。