打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C# Code Snippet - Byte array to object
userphoto

2010.12.07

关注

This .Net C# code snippet convert byte array to object. This functionuseful to convert back byte array data to its original objectrepresentation. Most common method to store binary data in database isas a byte array format. This function can be use to deserialize thosebyte array data (Serialized) to their original objects like image data..etc. This function uses System.IO andSystem.Runtime.Serialization.Formatters.Binary name spaces to convertbyte array to object. Modify the exception handling section as to yourproject requirements.

Note that it will be necessary to castthe returned generic Object from the deserialization method back intothe original type of object you passed in to the serialization methodoriginally.

01 /// <summary>
02 /// Function to get object from byte array
03 /// </summary>
04 /// <param name="_ByteArray">byte array to get object</param>
05 /// <returns>object</returns>
06 public object ByteArrayToObject(byte[] _ByteArray)
07 {
08     try
09     {
10         // convert byte array to memory stream
11         System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);
12  
13         // create new BinaryFormatter
14         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
15                     = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
16  
17         // set memory stream position to starting point
18         _MemoryStream.Position = 0;
19  
20         // Deserializes a stream into an object graph and return as a object.
21         return _BinaryFormatter.Deserialize(_MemoryStream);
22     }
23     catch (Exception _Exception)
24     {
25         // Error
26         Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
27     }
28  
29     // Error occured, return null
30     return null;
31 }


Hereis a simple example showing how to use above function(ByteArrayToObject). In this example we convert byte array variable(_ByteArray) to image and show the image in picturebox.

1 byte[] _ByteArray = .... some data ....;
2  
3 pictureBox1.Image = (Image)ByteArrayToObject(_ByteArray);


C# Keywords Used:

  • MemoryStream
  • BinaryFormatter
  • Deserialize
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, Byte Array, Byte array to object, Binary Data, Deserialize, BinaryFormatter, Store binary data in database
  • Programming Language : C# (C-Sharp)

External Resources:

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
ISerializable接口简析
C#实现序列化、压缩、解压缩、反序列化对象代码如下:
ListView控件的使用
C#调用webservice 时如何传递实体对象
深拷贝的通用方法
Python内置函数—bytearray
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服