Convert an object to a byte array.
//-----------------------------------------------------------------------
// <copyright file="Utility.cs" company="ParanoidMike">
// Copyright (c) ParanoidMike. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace ParanoidMike
{
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Win32;
/// <summary>
/// Reusable functions for many uses.
/// </summary>
public static class Utility
{
/// <summary>
/// Convert an object to a byte array.
/// Copied from http://snippets.dzone.com/posts/show/3897
/// </summary>
/// <param name="obj">
/// The object to be converted.
/// </param>
/// <returns>
/// The byte[] array to which the object is converted.
/// </returns>
public static byte[] ObjectToByteArray(object obj)
{
if (obj == null)
{
return null;
}
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
}
Related examples in the same category