C# 读写十六进制bin 文件

时间:2022-01-13 12:08:26

读一个十六进制的bin文件,在bin文件添加四行头,生成新的bin文件。bin文件可以用vs打开查看。

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

namespace ACU_004GEN
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private byte[] binContent;
        private string vendorCode = "";
        private string deviceType = "";
        private string hardwareVersion = "";
        private byte[] crc32 ;
        private byte[] checkSum;
        private byte[] firmwareLength ;

        private string sourceBinFile = "";
        private string saveBinFile = "";

        //private uint crc = 0xFFFFFFFF;
        private uint crc_function = 0xEDB88320;
        private uint crc32_reverse(byte[] buf)
        {
            byte i;
            uint crc = 0xFFFFFFFF;
            //uint crc_function = 0xEDB88320;
            foreach (byte bufByte in buf)
            {
                ; i <<= )
                {
                    )
                    {
                        crc >>= ;
                        crc ^= crc_function;
                    }
                    ;
                    )
                        crc ^= crc_function;
                }
            }
            return (crc);
        }

        private uint CheckSum(byte[] buf)
        {

            //uint crc = 0xFFFFFFFF;
            ;
            //uint crc_function = 0xEDB88320;
            foreach (byte bufByte in buf)
            {
                checkSum = checkSum + bufByte;

            }
            return (checkSum);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            rbtCheckSum.Checked = true;
            buttonGenerate.Enabled = false;
            linkLabelBinaryName.Text = null;
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void labelCheckSum_Click(object sender, EventArgs e)
        {

        }

        private void buttonImportBinary_Click(object sender, EventArgs e)
        {

            //openFileDialog1 = new OpenFileDialog();
            //OpenFileDialog dialog = new OpenFileDialog();
            openFileDialogImport.Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";
            openFileDialogImport.Title = string.Format("Open Firmware File");
            openFileDialogImport.FilterIndex = ;
            openFileDialogImport.RestoreDirectory = true;
            if (openFileDialogImport.ShowDialog() != DialogResult.Yes)
            {
                //sourceBinFile = openFileDialogImport.FileName;

                try
                {
                    if (!File.Exists(sourceBinFile))
                    {
                        return;
                    }

                    buttonGenerate.Enabled = true;                  

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void ReadWirteBinFile()
        {           

            using (FileStream fs = new FileStream(saveBinFile, FileMode.Create, FileAccess.Write))
            {
                , );
                WirteBin(fs, headerRow0, );

                ) + hardwareVersion;
                WirteBin(fs, headerRow1, );

                //byte[] headerRow2 = crc32 + firmwareLength;
                //WirteBin(fs, headerRow2, 2);
                fs.Position =  * ;
                if (rbtCRC32.Checked == true)
                {
                    fs.Write(crc32, , );
                }
                else
                {
                    fs.Write(checkSum, , );

                }
                fs.Position =  *  + ;
                fs.Write(firmwareLength, , );

                string headerRow3 = "\0";
                WirteBin(fs, headerRow3, );

                fs.Position =  * ;
                fs.Write(binContent, , binContent.Length);              

            }//end using

        }

        private void WirteBin(FileStream fs,string str,int row)
        {

            byte[] buffer  = System.Text.Encoding.ASCII.GetBytes(str);
            fs.Position =  * row;
            fs.Write(buffer, , str.Length);
        }

        private void buttonGenerate_Click(object sender, EventArgs e)
        {
            buttonImportBinary.Enabled = false;

            vendorCode = LeftAddZero(textBoxVendorCode.Text.Trim(), );
            deviceType = LeftAddZero(textBoxDeviceType.Text.Trim(), );
            hardwareVersion = LeftAddZero(textBoxHardwareVersion.Text.Trim(), );

            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";
            saveDlg.Title = string.Format("Save Binary File");
            saveDlg.FilterIndex = ;
            saveDlg.RestoreDirectory = true;
            if (saveDlg.ShowDialog() != DialogResult.Yes)
            {
                saveBinFile = saveDlg.FileName;
                try
                {
                    ReadWirteBinFile();
                    buttonGenerate.Enabled = false;

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    buttonImportBinary.Enabled = true;
                }
            }

            buttonImportBinary.Enabled = true;

        }

        private string RightAddZero(string str, int length)
        {
            string retStr = str;
            for (int i = str.Length;i< length;i++)
            {
                retStr = retStr + "\0";
            }

            return retStr;
        }

        private string LeftAddZero(string str, int length)
        {
            string retStr = str;
            for (int i = str.Length; i < length; i++)
            {
                retStr ="\0"+ retStr;
            }

            return retStr;
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            sourceBinFile = openFileDialogImport.FileName;

            linkLabelBinaryName.Text = sourceBinFile;
            binContent = File.ReadAllBytes(sourceBinFile);
            firmwareLength = System.BitConverter.GetBytes(binContent.Length);
            //Array.Reverse(firmwareLength);
            textBoxFileLength.Text = LeftAddZero(binContent.Length.ToString();
            uint crcTmp = crc32_reverse(binContent);
            crc32 = System.BitConverter.GetBytes(crcTmp);

            uint checkSumTmp = CheckSum(binContent);
            checkSum = System.BitConverter.GetBytes(checkSumTmp);

            //Array.Reverse(crc32);
            textBoxCRC32.Text = LeftAddZero(crcTmp.ToString();
            textBoxCheckSum.Text = LeftAddZero(checkSumTmp.ToString();
        }

    }
}