How to convert an object to a byte array in C#
By FoxLearn 10/28/2024 7:42:49 AM 129
To convert an object to a byte array in C#, you can use serialization.
How to convert an object to a byte array in C#?
The most common approach to convert an object to a byte array in the .NET Framework is to use the BinaryFormatter
.
This method requires the object to be marked as [Serializable]
, and it allows for easy serialization of the object into a byte array using a MemoryStream
.
For example:
public static byte[] ObjectToByteArray<T>(T obj) { if (obj != null) { using (MemoryStream ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, obj); return ms.ToArray(); } } return null; }
Usage
[Serializable] public class People { public int Id { get; set; } public string Name { get; set; } } //Main.cs People obj = new People { Id = 1, Name = "Tom" }; byte[] byteArray = ObjectToByteArray(obj);
Ensure that the class you are serializing is marked with [Serializable]
if you are using BinaryFormatter
.
Categories
Popular Posts
Spica Admin Dashboard Template
11/18/2024