C# 通过MemoryStream,BinaryWriter,BinaryReader读写字节数据

不用自己再去写各种数据类型转字节数组的方法了,用起来很方便,不过如果要和第三方程序通讯的话,需要搞清楚BinaryWriter和BinaryReader是怎么实现的,让下位机按照BinaryWriter和BinaryReader的方式传输数据,而且ms.GetBuffer()得到的数据貌似是直接返回的内部字节数组,数组的长度可能会严重大于实际数据的长度

using System;
using System.IO;

namespace ConsoleApp {
    class Program {
        static void Main(string[] args) {
            Model model = new Model {
                CmdID = 0x01,
                UserID = 9999,
                Name = "张三丰"
            };
            byte[] byteArray = Write(model);
            Model readData = Read(byteArray);
            Console.ReadKey();
        }
        class Model {
            public byte CmdID { get; set; }
            public int UserID { get; set; }
            public string Name { get; set; }
        }
        /// <summary>
        /// 将数据写入到字节数组中
        /// </summary>
        static byte[] Write(Model data) {
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(data.CmdID);  //写数据
            bw.Write(data.UserID);
            bw.Write(data.Name);
            return ms.GetBuffer();
        }
        /// <summary>
        /// 从字节数组中读取数
        /// </summary> 
        static Model Read(byte[] byteArray) {
            MemoryStream ms = new MemoryStream(byteArray);
            BinaryReader br = new BinaryReader(ms);
            return new Model {
                CmdID = br.ReadByte(),  //读数据
                UserID = br.ReadInt32(),
                Name = br.ReadString()
            };
        }
    }
}

 

上一篇:第九章面向复用的软件构造技术


下一篇:从MemoryStream生成ImageSource的最佳实践