Skip to content

Instantly share code, notes, and snippets.

@indication
Created March 11, 2011 08:09
Show Gist options
  • Save indication/865605 to your computer and use it in GitHub Desktop.
Save indication/865605 to your computer and use it in GitHub Desktop.
Serialize object wothout file
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Siri
{
static class Serializer
{
static public Encoding DefaultEncoding
{
get
{
return Encoding.Unicode;
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
static public string Serialize<T>(T obj)
{
return Serialize<T>(obj, DefaultEncoding);
}
static public string Serialize<T>(T obj, Encoding Encoding)
{
if (obj == null)
return string.Empty;
var _sb = new System.Text.StringBuilder();
var _setting = new XmlWriterSettings();
_setting.Encoding = Encoding;
using (var writer = System.Xml.XmlWriter.Create(_sb, _setting))
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, obj);
}
return _sb.ToString();
}
static public T Deserialize<T>(string _data)
{
return Deserialize<T>(_data, DefaultEncoding);
}
static public T Deserialize<T>(string _data, Encoding Encoding)
{
if (string.IsNullOrEmpty(_data))
return default(T);
try
{
using (var memoryStream = new MemoryStream(Encoding.GetBytes(_data.ToCharArray())))
using (var xml = XmlReader.Create(memoryStream))
{
var serializer = new XmlSerializer(typeof(T));
if (!serializer.CanDeserialize(xml))
{
return default(T);
}
var obj = serializer.Deserialize(xml);
if (obj is T)
{
return (T)obj;
}
else
{
return default(T);
}
}
}
catch
{
return default(T);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment