Files
Common-VS2019/SacsStandardBase/Base/Utils/SerializableUtil.cs
T
2021-05-05 15:36:28 +01:00

83 lines
2.7 KiB
C#

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
namespace Sarand.Net.Standard.Base.Utils
{
//=======================================================================
public static class SerializableUtil
{
//-------------------------------------------------------------------
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T DeepCopy<T>(T source)
{
if (!typeof(T).IsSerializable)
throw new ArgumentException("The type must be serializable.", "source");
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
return default(T);
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
//-------------------------------------------------------------------
// Serialize.
public static String Serialize<T>(T source)
{
if (!typeof(T).IsSerializable) throw new ArgumentException("The type must be serializable.", "source");
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null)) return "";
// Serialise to String.
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new MemoryStream())
using (StreamReader streamReader = new StreamReader(stream))
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return streamReader.ReadToEnd();
}
}
//-------------------------------------------------------------------
// Serialize using XML.
public static String ToXml<T>(T source)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (Stream stream = new MemoryStream())
{
serializer.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}
public static T FromXml<T>(String data)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(data ?? "")))
{
return (T)serializer.Deserialize(stream);
}
}
//-------------------------------------------------------------------
}
//=======================================================================
}