|
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace CodeProject.Batte.ObjectMastery
{
/*
* StringExtensions.cs
* Author: John Batte
* Last Modified: 1/5/2009
* See http://www.codeproject.com/info/cpol10.aspx for license details
*/
/// <summary>
/// Provides object serialization extensions for strings.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Converts the string to an object instance
/// of the specified type. Assumes that the string
/// was created using object.ToBinaryString().
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="serializedObject">The string.</param>
/// <returns>The converted object instance.</returns>
public static T ToObject<T>(this string serializedObject)
{
var formatter = new BinaryFormatter();
var stream = new MemoryStream(Convert.FromBase64String(serializedObject));
var graph = formatter.Deserialize(stream) as ObjectGraph;
return graph == null ? default(T) : (T) graph.CreateInstance(true);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I'm a professional developer with over 9 years of experience in advanced C# development. I've worked extensively with every phase of the SDLC and have developed and deployed many enterprise solutions using the latest .Net technologies. Please let me know if you have any suggestions or questions.