C# 将结构体转化为byte数组,byte数组转化为结构体

 1.将结构体转化为byte数组

#region        
        /// <summary>
        /// 结构体转为byte数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] StructToBytes<T>(T obj)
        {
            int size = Marshal.SizeOf(typeof(T));
            IntPtr bufferPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(obj, bufferPtr, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(bufferPtr, bytes, 0, size);
                return bytes;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in StructToBytes ! " + ex.Message);
            }
            finally
            {
                Marshal.FreeHGlobal(bufferPtr);
            }
        }
        #endregion

2.byte数组转化为结构体

#region 方法2.byte数组转化为结构体
        /// <summary>
        /// byte数组转化为结构体
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object BytesToStuct(byte[] bytes, Type type)
        {
            //获得结构体的大小
            int size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                //返回空
                return null;
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return obj;
        }
        #endregion

3.将结构体转化为数组后写入dat文件数组

byte[] b = StructToBytes<userguanbiao>(ugb);//将结构体转化为byte数组
                writeBATFiles(b);//将数组写入dat文件

 4.从文件中读取数组并转化为结构体显示code

#region button1.读取dat文件并转化为结构体
        public void button1_Click(object sender, EventArgs e)
        {
            string filePath = Application.StartupPath;
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            string endfilePath = path.SelectedPath;

            if (Directory.Exists(endfilePath) && Directory.Exists(filePath))
            {
                MoveFile(endfilePath, filePath);
            }
            else
            {
                MessageBox.Show("路径不存在!");
                return;
            }
            Array.Clear(lt,0,12);
            tanknum = 0;
            Array.Clear(lt1, 0, 1);
            
            byte[] bytData = readBATFile();//以字节数组形式读出dat文件
            if (bytData == null)
            {
                MessageBox.Show("tanktable.dat文件不存在,请先生成tanktable.dat,或者将该文件复制到程序运行目下!");
                return;
            }
            userguanbiao lol =(userguanbiao)BytesToStuct(bytData,typeof(userguanbiao));//把数组转化为结构体
            ugb = lol;
            DataTable dt = new DataTable();
            dt.Columns.Add("tankno", typeof(string)); //数据类型为 文本
            dt.Columns.Add("tankH", typeof(string)); //数据类型为 文本
            dt.Columns.Add("tankCap", typeof(string)); //数据类型为 文本
            dt.Columns.Add("totalH", typeof(string)); //数据类型为 文本
            dt.Columns.Add("ID", typeof(string)); //数据类型为 文本
            for (int i = 0; i < lol.ltPonsion.Length; i++)
            {
                int littleid = 1;
                if (lol.ltPonsion[i].number != 0)
                {
                    
                    for (int k = 0; k < lol.ltPonsion[i].number; k++)
                    {
                        dt.Rows.Add((i + 1).ToString(), lol.ltPonsion[i].guangao[k].ToString(), lol.ltPonsion[i].guanrong[k].ToString(), lol.ltPonsion[i].guangao[lol.ltPonsion[i].number - 1].ToString(), littleid.ToString());//Add大家参数的数据顺序要和dt中的列顺对应
                        littleid++;

                    }
                    tanknum++;
                }
                lt[i] = lol.ltPonsion[i];
            }
            readdts = dt;
            dgvStruct.DataSource = dt;
        }
        #endregion