How to convert an object to a byte array in C#
By FoxLearn 10/28/2024 7:42:49 AM 4
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
.
- How to fix 'DevExpress.Images.ImageResourceCache.Default.GetImage' not working
- How to convert byte array to an object in C#
- How to get index of element in array C# LINQ
- How to find index of item in array in C#
- How to get AssemblyTitle in C#
- How to kill process by name in C#
- How to Read data from Google Sheet in C# using HttpRequest without Speadsheet API
- How to set DataSource for RDLC Report using Report Viewer in C#
Categories
Popular Posts
How to sign a powershell script
10/03/2024