本帖最后由 shiy720 于 2024-6-19 11:25 编辑
在 .NET 8 中,BinaryFormatter 类已标记为过时,不再建议使用。 相反,您可以使用BinaryWriter 和 BinaryReader 类来打包和解压缩数据。 下面是在 .NET 8 中打包和解压缩数据的更新示例: - using System;
- using System.IO;
- public class Packet
- {
- public int Id { get; set; }
- public string Message { get; set; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Packet packet = new Packet { Id = 1, Message = "Hello, World!" };
- using (MemoryStream stream = new MemoryStream())
- {
- using (BinaryWriter writer = new BinaryWriter(stream))
- {
- writer.Write(packet.Id);
- writer.Write(packet.Message);
- byte[] packedData = stream.ToArray();
- // Send packed data over the network
- Console.WriteLine("Packed data: ");
- foreach (byte b in packedData)
- {
- Console.Write($"{b:X2} ");
- }
- Console.WriteLine();
- }
- }
- }
- }
复制代码 如果要解包 你可以使用 BinaryReader 类来处理
- class Program
- {
- static void Main(string[] args)
- {
- byte[] packedData = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21 };
- using (MemoryStream stream = new MemoryStream(packedData))
- {
- using (BinaryReader reader = new BinaryReader(stream))
- {
- int id = reader.ReadInt32();
- string message = reader.ReadString();
- Packet packet = new Packet { Id = id, Message = message };
- Console.WriteLine($"Unpacked data: Id={packet.Id}, Message={packet.Message}");
- }
- }
- }
- }
复制代码 |