Last active
August 29, 2015 14:24
-
-
Save digioz/e40c8dc112fadd289b9d to your computer and use it in GitHub Desktop.
Serialize and Deserialize Any C# Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Xml.Serialization; | |
namespace digioz.BLL | |
{ | |
public static class Utilities | |
{ | |
// Usage Serialize: SerializeObject(links, typeof(List<Link>), @"C:\temp\links.xml"); | |
// Usage Deserialize: List<Link> links2 = (List<Link>)DeserializeObject(@"C:\temp\links.xml", typeof(List<Link>)); | |
/// <summary> | |
/// Method to Serialize any C# Object | |
/// </summary> | |
/// <param name="objectInstance"></param> | |
/// <param name="objectType"></param> | |
/// <param name="saveFile"></param> | |
/// <returns></returns> | |
public static bool SerializeObject(object objectInstance, Type objectType, string saveFile) | |
{ | |
try | |
{ | |
XmlSerializer loMessageSerialize = new XmlSerializer(objectType); | |
StreamWriter loWriteStream = new StreamWriter(saveFile); | |
loMessageSerialize.Serialize(loWriteStream, objectInstance); | |
loWriteStream.Close(); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message.ToString()); | |
} | |
return true; | |
} | |
/// <summary> | |
/// Method to Deserialize any C# Object | |
/// </summary> | |
/// <param name="loadFile"></param> | |
/// <param name="objectType"></param> | |
/// <returns></returns> | |
public static object DeserializeObject(string loadFile, Type objectType) | |
{ | |
object objectInstance = new object(); | |
try | |
{ | |
XmlSerializer loMessage = new XmlSerializer(objectType); | |
StreamReader loStreamReader = new StreamReader(loadFile); | |
objectInstance = loMessage.Deserialize(loStreamReader); | |
loStreamReader.Close(); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
return objectInstance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment