How to convert byte array to an object in C#
By FoxLearn 10/28/2024 7:47:04 AM 90
To convert a byte array back to an object in C#, you can use deserialization.
How to convert byte array to an object in C#?
For example:
public static T FromByteArray<T>(byte[] data) { if (data != null) { using (MemoryStream ms = new MemoryStream(data)) { object obj = new BinaryFormatter().Deserialize(ms); return (T)obj; } } return default(T); }
Usage
[Serializable] public class People { public int Id { get; set; } public string Name { get; set; } } //Main.cs byte[] byteArray = /* your byte array here */; People obj = ByteArrayToObject<People>(byteArray);
When using BinaryFormatter
, make sure the class is marked with [Serializable]
.
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024