BinaryFormatter序列化与反序列化(C#)

版权声明:本文为博主原创文章,未经博主允许不得转载。    https://blog.csdn.net/u013667895/article/details/78478458
BinaryFormatter以二进制格式序列化和反序列化对象。

BinaryFormatte序列化:将对象转化成二进制,BinaryFormatte反序列化就是将二进制转化为对象;

命名空间: System.Runtime.Serialization.Formatters;

最常用的两个方法:


Deserialize(Stream)    将指定的流反序列化成对象
Serialize(Stream, Object)    将对象序列化到给定的流

两个常用的属性:


Serializable    表示可以被序列化
NonSerializable    屏蔽被序列化

例子:


using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
 
namespace Binaryformats
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Person p = new Person();
            p.Sex = 1;
            p.Age = 21;
            p.Name = "dfr";
            byte[] serBytes = BinaryFormat.Serialize(p); //序列化
            Person pp = (Person) BinaryFormat.Deserialize(serBytes); //反序列化,object类转化成自己定义的
            Console.WriteLine(pp.Name);
            Console.ReadLine();
        }
 
        [Serializable]
        private class Person //用Serializable做了标记,标识可以被序列化
        {
            private int _age;
 
            [NonSerialized] private string _name; //用NonSerialized做了标记,标识该字段屏蔽序列化
 
            private int _sex;
 
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
 
            public int Sex
            {
                get { return _sex; }
                set { _sex = value; }
            }
 
            public int Age
            {
                get { return _sex; }
                set { _sex = value; }
            }
        }
    }
 
    public class BinaryFormat
    {
        public static byte[] Serialize(Object Urobject) //序列化 返回byte[]类型
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream memory = new MemoryStream();
            bf.Serialize(memory, Urobject);
            byte[] bytes = memory.GetBuffer();
            memory.Close();
            return bytes;
        }
 
        public static object Deserialize(byte[] bytes) //反序列化,返回object类型的
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream memory = new MemoryStream(bytes);
            object ss = bf.Deserialize(memory);
            memory.Close();
            return ss;
        }
    }
}

NonSerialized作用:被标记的字段都赋成空

结果:


--------------------- 
作者:一木一百 
来源:CSDN 
原文:https://blog.csdn.net/u013667895/article/details/78478458 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

object与byte[]的相互转换:

 

 
  1. /// <summary>

  2. /// 工具类:对象与二进制流间的转换

  3. /// </summary>

  4. class ByteConvertHelper

  5. {

  6. /// <summary>

  7. /// 将对象转换为byte数组

  8. /// </summary>

  9. /// <param name="obj">被转换对象</param>

  10. /// <returns>转换后byte数组</returns>

  11. public static byte[] Object2Bytes(object obj)

  12. {

  13. byte[] buff;

  14. using (MemoryStream ms = new MemoryStream())

  15. {

  16. IFormatter iFormatter = new BinaryFormatter();

  17. iFormatter.Serialize(ms, obj);

  18. buff = ms.GetBuffer();

  19. }

  20. return buff;

  21. }

  22.  
  23. /// <summary>

  24. /// 将byte数组转换成对象

  25. /// </summary>

  26. /// <param name="buff">被转换byte数组</param>

  27. /// <returns>转换完成后的对象</returns>

  28. public static object Bytes2Object(byte[] buff)

  29. {

  30. object obj;

  31. using (MemoryStream ms = new MemoryStream(buff))

  32. {

  33. IFormatter iFormatter = new BinaryFormatter();

  34. obj = iFormatter.Deserialize(ms);

  35. }

  36. return obj;

  37. }

  38. }

 

 

文件与byte数组相互转换:

 

 
  1. /// <summary>

  2. /// 工具类:文件与二进制流间的转换

  3. /// </summary>

  4. class FileBinaryConvertHelper

  5. {

  6. /// <summary>

  7. /// 将文件转换为byte数组

  8. /// </summary>

  9. /// <param name="path">文件地址</param>

  10. /// <returns>转换后的byte数组</returns>

  11. public static byte[] File2Bytes(string path)

  12. {

  13. if(!File.Exists(path))

  14. {

  15. return new byte[0];

  16. }

  17.  
  18. FileInfo fi = new FileInfo(path);

  19. byte[] buff = new byte[fi.Length];

  20.  
  21. FileStream fs = fi.OpenRead();

  22. fs.Read(buff, 0, Convert.ToInt32(fs.Length));

  23. fs.Close();

  24.  
  25. return buff;

  26. }

  27.  
  28. /// <summary>

  29. /// 将byte数组转换为文件并保存到指定地址

  30. /// </summary>

  31. /// <param name="buff">byte数组</param>

  32. /// <param name="savepath">保存地址</param>

  33. public static void Bytes2File(byte[] buff, string savepath)

  34. {

  35. if (File.Exists(savepath))

  36. {

  37. File.Delete(savepath);

  38. }

  39.  
  40. FileStream fs = new FileStream(savepath, FileMode.CreateNew);

  41. BinaryWriter bw = new BinaryWriter(fs);

  42. bw.Write(buff, 0, buff.Length);

  43. bw.Close();

  44. fs.Close();

  45. }

  46. }

原文:http://my.oschina.net/Tsybius2014/blog/352409

 

新增,

Image与byte数组相互转换:

 

 
  1. /// <summary>

  2. /// 从byte数组创建Image

  3. /// </summary>

  4. public static Image Bytes2Image(byte[] bytes)

  5. {

  6. System.IO.MemoryStream stream = new System.IO.MemoryStream();

  7. stream.Write(bytes, 0, bytes.Length);

  8. Image image = Image.FromStream(stream);

  9.  
  10. return image;

  11. }

  12.  
  13. /// <summary>

  14. /// 将Image转化为byte数组,使用缓存文件中转

  15. /// </summary>

  16. public static byte[] Image2Bytes_tmpFile(Image image, ImageFormat imageFormat = null)

  17. {

  18. if (imageFormat == null) imageFormat = ImageFormat.Jpeg;

  19. String tmpFilePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Ticks + ".stream";

  20. image.Save(tmpFilePath, imageFormat); // 保存图像到文件

  21.  
  22. byte[] bytes = File2Bytes(tmpFilePath); // 从文件中获取字节数组

  23. if (File.Exists(tmpFilePath)) File.Delete(tmpFilePath); //删除文件

  24.  
  25. return bytes;

  26. }

 

 

反序列化无法找到程序集

提示找不到程序集.

      原因是序列化时把序列化类的命名空间等信息保存了,但应用程序和类库的命名空间可能是

不一样的,所以提示找不到程序集.

      解决方法如下:

      方法1.将dll加入强名称,注册到全局程序集缓存中

      方法2.在反序列化使用的IFormatter 对象加入Binder 属性,使其获取要反序列化的对象所在的程序集

      示例如下:

 public void DeSerialize( byte [] data, int offset)
  {
     IFormatter formatter = new BinaryFormatter();
     formatter.Binder = new UBinder();
     MemoryStream stream = new MemoryStream(data, offset, stringlength);
    this .m_bodyobject = ( object )formatter.Deserialize(stream);

 
public class UBinder:SerializationBinder
  {
    public override Type BindToType( string assemblyName, string typeName)
       {
        Assembly ass = Assembly.GetExecutingAssembly();
       return ass.GetType(typeName);
     } 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/scgyyu/archive/2009/06/02/4232371.aspx

 

项目中碰到要反序列化第三方提供的数据包。

对方序列化时对象为 namespaceA.packetA

但他提供的dll文件命名空间却是 namespaceB.packetA

导致我反序列化失败,最后通过上面介绍的方式实现反序列化

public class UBinder:SerializationBinder

{
    public override Type BindToType( string assemblyName, string typeName)
    {

        if (typeName.EndsWith("packetA")) return typeof(namespaceB.packetA);
        Assembly ass = Assembly.GetExecutingAssembly();
       return ass.GetType(typeName);
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值