77 lines
2.6 KiB
C#
77 lines
2.6 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Xml;
|
|
using System.Xml.Serialization;
|
|
namespace SPSolutions.Serialization
|
|
{
|
|
public static class SerializationUtil
|
|
{
|
|
public static string Serialize<T>(T objToSerialize) where T : class
|
|
{
|
|
if (objToSerialize == null)
|
|
{
|
|
throw new ArgumentNullException("objToSerialize");
|
|
}
|
|
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
|
|
StringWriter stringWriter = new StringWriter();
|
|
xmlSerializer.Serialize(stringWriter, objToSerialize);
|
|
return stringWriter.ToString();
|
|
}
|
|
public static T Deserialize<T>(string stringToDeserialize) where T : class
|
|
{
|
|
if (string.IsNullOrEmpty(stringToDeserialize))
|
|
{
|
|
return default(T);
|
|
}
|
|
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
|
|
StringReader textReader = new StringReader(stringToDeserialize);
|
|
return (T)((object)xmlSerializer.Deserialize(textReader));
|
|
}
|
|
public static string SerializeObject(object objToSerialize, Type typ)
|
|
{
|
|
MemoryStream memoryStream = new MemoryStream();
|
|
XmlSerializer xmlSerializer = new XmlSerializer(typ);
|
|
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
|
|
xmlSerializer.Serialize(xmlTextWriter, objToSerialize);
|
|
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
|
|
return SerializationUtil.UTF8ByteArrayToString(memoryStream.ToArray());
|
|
}
|
|
public static object DeserializeObject(string stringToDeserialize, Type typ)
|
|
{
|
|
if (string.IsNullOrEmpty(stringToDeserialize))
|
|
{
|
|
return null;
|
|
}
|
|
XmlSerializer xmlSerializer = new XmlSerializer(typ);
|
|
MemoryStream memoryStream = new MemoryStream(SerializationUtil.StringToUTF8ByteArray(stringToDeserialize));
|
|
new XmlTextWriter(memoryStream, Encoding.UTF8);
|
|
return xmlSerializer.Deserialize(memoryStream);
|
|
}
|
|
public static string UTF8ByteArrayToString(byte[] characters)
|
|
{
|
|
UTF8Encoding uTF8Encoding = new UTF8Encoding();
|
|
return uTF8Encoding.GetString(characters);
|
|
}
|
|
public static byte[] StringToUTF8ByteArray(string pXmlString)
|
|
{
|
|
UTF8Encoding uTF8Encoding = new UTF8Encoding();
|
|
if (string.IsNullOrEmpty(pXmlString))
|
|
{
|
|
return null;
|
|
}
|
|
return uTF8Encoding.GetBytes(pXmlString);
|
|
}
|
|
public static string GetAssemblyManifestResourceFileContent(string filename)
|
|
{
|
|
Assembly callingAssembly = Assembly.GetCallingAssembly();
|
|
Stream manifestResourceStream = callingAssembly.GetManifestResourceStream(callingAssembly.GetName().Name + "." + filename);
|
|
StreamReader streamReader = new StreamReader(manifestResourceStream);
|
|
string result = streamReader.ReadToEnd();
|
|
streamReader.Close();
|
|
return result;
|
|
}
|
|
}
|
|
}
|