代码改变世界

C#读取二进制文件并保存16进制字符串

2013-03-21 14:06  渔者  阅读(1582)  评论(0编辑  收藏  举报

private static readonly int CHUNK_ALL_SIZE = 308;      //总的区间长度

private static readonly int CHUNK_DATA_SIZE = 288;      //Key数据长度

private static readonly int CHUNK_CHECKSUM_SIZE = 20;   //Key的CheckSum长度

 

private void btnSaveDB_Click(object sender, EventArgs e)

{

        try

        {

                this.Cursor = Cursors.AppStarting;

 

 

                //秒表统计运行时间

                Stopwatch myWatch = new Stopwatch();

                myWatch.Start();

 

 

                int nTotalQty = 0;

                int n = 0;

                string sData = "";

                string sKey = "";

                string sKeyCheckSUM = "";       //文件中的CheckSum

                string sSHA1_CheckSum = "";         //通过SHA1算法计算的CheckSum

                string sql = "";

 

                string path = "";

                path = txtFilePath.Text.Trim();

 

                string serverName = "";

                string dbName = "";

                int ptlt = 0;

                int maxID = 0;

 

                #region 判断输入

                if (path.Length == 0)

                {

                        this.Cursor = Cursors.Default;

                        MessageBox.Show("请输入FilePath");

                        txtFilePath.Focus();

                        return;

                }

                if (txtServerName.Text.Trim().Length == 0)

                {

                        this.Cursor = Cursors.Default;

                        MessageBox.Show("请输入ServerName");

                        txtServerName.Focus();

                        return;

                }

                if (txtDBName.Text.Trim().Length == 0)

                {

                        this.Cursor = Cursors.Default;

                        MessageBox.Show("请输入DBName");

                        txtDBName.Focus();

                        return;

                }

                if (this.cboPTLT.SelectedIndex < 0)

                {

                        this.Cursor = Cursors.Default;

                        MessageBox.Show("请输入选择试产、量产");

                        cboPTLT.Focus();

                        return;

                }

                #endregion

 

                serverName = txtServerName.Text.Trim();

                dbName = txtDBName.Text.Trim();

                ptlt = this.cboPTLT.SelectedIndex;

 

 

                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))

                {

                        using (BinaryReader br = new BinaryReader(fs, new ASCIIEncoding()))

                        {

                                byte[] chunk;

                                byte[] chunkCheck = new byte[CHUNK_DATA_SIZE];

 

                                //读取总数量,前4个byte

                                chunk = br.ReadBytes(4);

                                nTotalQty = int.Parse(ByteToHexString(chunk));

 

                                //获取一个 Key

                                chunk = br.ReadBytes(CHUNK_ALL_SIZE);       //308个byte = Key(288个byte) + CheckSum(20个byte)

 

                                //转换成String

                                sData = ByteToHexString(chunk);

                                if (sData.Length > 0)

                                {

                                        sKey = sData.Substring(0, CHUNK_DATA_SIZE * 2);

                                        sKeyCheckSUM = sData.Substring(CHUNK_DATA_SIZE * 2);

 

                                        //meiwm add 2013/3/22, 通过SHA1算法计算CheckSum

                                        //chunkCheck = StringToHexByte(sKey);      //方法1: string转成byte数组

                                        //Array.Copy(chunk, chunkCheck, CHUNK_DATA_SIZE);     //方法2: 直接获取288位的数组

                                        System.Buffer.BlockCopy(chunk, 0, chunkCheck, 0, CHUNK_DATA_SIZE);      //方法3: BlockCopy比Copy方法快

                                        sSHA1_CheckSum = GetSHA1(chunkCheck);

                                        if (sKeyCheckSUM != sSHA1_CheckSum)

                                        {

                                                MessageBox.Show("CheckSUM error!");

                                                return;

                                        }

                                }

 

                                while (chunk.Length > 0)

                                {

                                        n++;

 

 

                                        sData = "";

                                        sKey = "";

                                        sKeyCheckSUM = "";

                                        chunk = br.ReadBytes(CHUNK_ALL_SIZE);       //再获取一个 Key

                                        sData = ByteToHexString(chunk);

                                        if (sData.Length > 0)

                                        {

                                                sKey = sData.Substring(0, CHUNK_DATA_SIZE * 2);

                                                sKeyCheckSUM = sData.Substring(CHUNK_DATA_SIZE * 2);

 

                                                //通过SHA1算法计算CheckSum

                                                //chunkCheck = StringToHexByte(sKey);      //方法1: string转成byte数组

                                                //Array.Copy(chunk, chunkCheck, CHUNK_DATA_SIZE);     //方法2: 直接获取288位的数组

                                                System.Buffer.BlockCopy(chunk, 0, chunkCheck, 0, CHUNK_DATA_SIZE);      //方法3: BlockCopy比Copy方法快

                                                sSHA1_CheckSum = GetSHA1(chunkCheck);

                                                if (sKeyCheckSUM != sSHA1_CheckSum)

                                                {

                                                        this.Cursor = Cursors.Default;

                                                        MessageBox.Show("CheckSUM error!");

                                                        return;

                                                }

                                        }

                                }

                        }

                }

 

 

                this.Cursor = Cursors.Default;

 

 

                //秒表统计时间

                myWatch.Stop();

                long myUseTime = myWatch.ElapsedMilliseconds;

                MessageBox.Show("用时: " + myUseTime.ToString() + " ms");

 

 

                MessageBox.Show("SaveToDatabase OK!");

        }

        catch (Exception ex)

        {

                this.Cursor = Cursors.Default;

                MessageBox.Show(ex.Message);

        }

}

 

private void btnSaveFile_Click(object sender, EventArgs e)

{

        try

        {

                this.Cursor = Cursors.AppStarting;

 

 

                //秒表统计运行时间

                Stopwatch myWatch = new Stopwatch();

                myWatch.Start();

 

 

                int nTotalQty = 0;

                int n = 0;

                string sData = "";

                string sKey = "";

                string sKeyCheckSUM = "";

 

                string path = "";

                path = txtFilePath.Text.Trim();

 

                string writeFileName = "KeyData.txt";

 

                int nSaveFileQty = 0;

 

 

                #region 判断输入

                if (path.Length == 0)

                {

                        this.Cursor = Cursors.Default;

                        MessageBox.Show("请输入FilePath");

                        txtFilePath.Focus();

                        return;

                }

                if (this.txtSaveFileQty.Text.Trim().Length == 0)

                {

                        this.Cursor = Cursors.Default;

                        MessageBox.Show("请输入SaveFileQty");

                        txtSaveFileQty.Focus();

                        return;

                }

                #endregion

 

 

                nSaveFileQty = int.Parse(this.txtSaveFileQty.Text.Trim());

 

                //使用FileStream/StreamWriter写普通格式文件

                using (FileStream fswrite = new FileStream(writeFileName, FileMode.Create))

                {

                        using (StreamWriter sw = new StreamWriter(fswrite))

                        {

                                //使用FileStream/BinaryReader读取二进制文件

                                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))

                                {

                                        using (BinaryReader br = new BinaryReader(fs, new ASCIIEncoding()))

                                        {

                                                byte[] chunk;

 

                                                //读取总数量,前4个byte

                                                chunk = br.ReadBytes(4);        //前4个byte是数量

                                                nTotalQty = int.Parse(ByteToHexString(chunk));

 

                                                //获取一个 Key

                                                chunk = br.ReadBytes(CHUNK_ALL_SIZE);       //308个byte = Key(288个byte) + CheckSum(20个byte)

 

                                                //转换成String

                                                sData = ByteToHexString(chunk);

                                                //if (sData.Length > 0)

                                                //{

                                                //    sKey = sData.Substring(0, 288 * 2);

                                                //    sKeyCheckSUM = sData.Substring(288 * 2);

                                                //}

 

                                                while (chunk.Length > 0 & n < nSaveFileQty)

                                                {

                                                        n++;

 

 

                                                        //保存到文件

                                                        sw.WriteLine(sData);

 

 

                                                        sData = "";

                                                        sKey = "";

                                                        sKeyCheckSUM = "";

                                                        chunk = br.ReadBytes(CHUNK_ALL_SIZE);       //再获取一个 Key

                                                        sData = ByteToHexString(chunk);

                                                        //if (sData.Length > 0)

                                                        //{

                                                        //    sKey = sData.Substring(0, 288 * 2);

                                                        //    sKeyCheckSUM = sData.Substring(288 * 2);

                                                        //}

                                                }

                                        }

                                }

                        }

 

                }

 

                this.Cursor = Cursors.Default;

 

 

                //秒表统计时间

                myWatch.Stop();

                long myUseTime = myWatch.ElapsedMilliseconds;

                MessageBox.Show("用时: " + myUseTime.ToString() + " ms");

 

 

                MessageBox.Show("SaveToFile OK!");

 

        }

        catch (Exception ex)

        {

                this.Cursor = Cursors.Default;

                MessageBox.Show(ex.Message);

        }

}

 

 

/// <summary>

/// Byte数组转成String

/// </summary>

/// <param name="bytes"></param>

/// <returns></returns>

private string ByteToHexString(byte[] bytes)

{

        string str = string.Empty;

        if (bytes != null)

        {

                for (int i = 0; i < bytes.Length; i++)

                {

                        str += bytes[i].ToString("X2");

                }

        }

        return str;

}

 

/// <summary>

/// String转成Byte数组

/// </summary>

/// <param name="str"></param>

/// <returns></returns>

private byte[] StringToHexByte(string str)

{

        str = str.Replace(" ", "");

        if ((str.Length % 2) != 0)

        {

                str += "";

        }

        byte[] bytes = new byte[str.Length / 2];

        for (int i = 0; i < bytes.Length; i++)

        {

                bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);

        }

        return bytes;

}

 

 

private string GetSHA1(string str)

{

        StringBuilder sb = new StringBuilder();

        foreach (byte b in System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(str)))

        {

                sb.Append(b.ToString("X2"));

        }

        return sb.ToString();

}

 

/// <summary>

/// 通过byte数组使用SHA1加密算法后返回string

/// </summary>

/// <param name="bytes"></param>

/// <returns></returns>

private string GetSHA1(byte[] bytes)

{

        StringBuilder sb = new StringBuilder();

        foreach (byte b in System.Security.Cryptography.SHA1.Create().ComputeHash(bytes))

        {

                sb.Append(b.ToString("X2"));

        }

        return sb.ToString();

}