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.
02 | /// Function to get object from byte array |
04 | /// <param name="_ByteArray">byte array to get object</param> |
05 | /// <returns>object</returns> |
06 | public object ByteArrayToObject( byte [] _ByteArray) |
11 | System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray); |
14 | System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter |
15 | = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); |
18 | _MemoryStream.Position = 0; |
21 | return _BinaryFormatter.Deserialize(_MemoryStream); |
23 | catch (Exception _Exception) |
26 | Console.WriteLine( "Exception caught in process: {0}" , _Exception.ToString()); |
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 ....; |
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:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。