Skip to content

Instantly share code, notes, and snippets.

@ForeverZer0
Last active August 31, 2018 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ForeverZer0/e433a29b6bd9185bdc2ccfafd4b917af to your computer and use it in GitHub Desktop.
Save ForeverZer0/e433a29b6bd9185bdc2ccfafd4b917af to your computer and use it in GitHub Desktop.
Simple utility methods for reading/writing objects decorated with DataContractAttribute in XML format.
public static bool Serialize<T>(T obj, Stream stream)
{
try
{
var xml = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
var serializer = new DataContractSerializer(typeof(T));
using (var writer = XmlWriter.Create(stream, xml))
{
serializer.WriteObject(writer, obj);
}
return true;
}
catch (Exception)
{
return false;
}
}
public static bool Serialize<T>(T obj, string filename)
{
try
{
using (var stream = File.Open(filename, FileMode.Create, FileAccess.Write))
{
return Serialize(obj, stream);
}
}
catch (Exception e)
{
return false;
}
}
public static object Deserialize(Type type, string filename)
{
try
{
using (var stream = File.OpenRead(filename))
{
return Deserialize(type, stream);
}
}
catch (Exception)
{
return null;
}
}
public static object Deserialize(Type type, Stream stream)
{
try
{
var serializer = new DataContractSerializer(type);
return serializer.ReadObject(stream);
}
catch (Exception)
{
return null;
}
}
public static T Deserialize<T>(string filename)
{
try
{
using (var stream = File.OpenRead(filename))
{
return (T) Deserialize(typeof(T), stream);
}
}
catch (Exception)
{
return default(T);
}
}
public static T Deserialize<T>(Stream stream) => (T) Deserialize(typeof(T), stream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment