找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 29|回复: 0

[工具类] .net8 C# 封包与解包 BinaryFormatter 类已标记为过时

[复制链接] IP属地:广东省广州市
发表于 2024-6-19 11:23:28 | 显示全部楼层 |阅读模式
本帖最后由 shiy720 于 2024-6-19 11:25 编辑

在 .NET 8 中,BinaryFormatter 类已标记为过时,不再建议使用。
相反,您可以使用BinaryWriter 和 BinaryReader 类来打包和解压缩数据。
下面是在 .NET 8 中打包和解压缩数据的更新示例:
  1. using System;
  2. using System.IO;

  3. public class Packet
  4. {
  5.     public int Id { get; set; }
  6.     public string Message { get; set; }
  7. }

  8. class Program
  9. {
  10.     static void Main(string[] args)
  11.     {
  12.         Packet packet = new Packet { Id = 1, Message = "Hello, World!" };

  13.         using (MemoryStream stream = new MemoryStream())
  14.         {
  15.             using (BinaryWriter writer = new BinaryWriter(stream))
  16.             {
  17.                 writer.Write(packet.Id);
  18.                 writer.Write(packet.Message);

  19.                 byte[] packedData = stream.ToArray();

  20.                 // Send packed data over the network
  21.                 Console.WriteLine("Packed data: ");
  22.                 foreach (byte b in packedData)
  23.                 {
  24.                     Console.Write($"{b:X2} ");
  25.                 }
  26.                 Console.WriteLine();
  27.             }
  28.         }
  29.     }
  30. }
复制代码
如果要解包 你可以使用 BinaryReader 类来处理
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.         byte[] packedData = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21 };

  6.         using (MemoryStream stream = new MemoryStream(packedData))
  7.         {
  8.             using (BinaryReader reader = new BinaryReader(stream))
  9.             {
  10.                 int id = reader.ReadInt32();
  11.                 string message = reader.ReadString();

  12.                 Packet packet = new Packet { Id = id, Message = message };

  13.                 Console.WriteLine($"Unpacked data: Id={packet.Id}, Message={packet.Message}");
  14.             }
  15.         }
  16.     }
  17. }
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|西兴社区 ( 蜀ICP备2022005627号 )|网站地图

GMT+8, 2024-9-8 11:33 , Processed in 0.615428 second(s), 21 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表