mirror of
https://gitlab.com/walljm/dynamicbible.git
synced 2025-07-26 00:39:48 -04:00
69 lines
1.9 KiB
C#
69 lines
1.9 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace VAE.Common.Serialization
|
|
{
|
|
public static class XML
|
|
{
|
|
public static bool SaveData(object o, string path)
|
|
{
|
|
File.WriteAllText(path, Serialize(o));
|
|
|
|
return true;
|
|
}
|
|
|
|
public static bool SaveData(object o)
|
|
{
|
|
return SaveData(o, o.GetType().Name + ".xml");
|
|
}
|
|
|
|
public static object GetData(Type t, string path, EncodingType enc = EncodingType.ASCII)
|
|
{
|
|
if (File.Exists(path))
|
|
{
|
|
object o = Deserialize(File.ReadAllText(path), t, enc);
|
|
|
|
return o;
|
|
}
|
|
|
|
return Activator.CreateInstance(t);
|
|
}
|
|
|
|
public static object GetData(Type t)
|
|
{
|
|
return GetData(t, t.Name + ".xml");
|
|
}
|
|
|
|
public static string Serialize(object o)
|
|
{
|
|
XmlSerializer serializer = new XmlSerializer(o.GetType());
|
|
MemoryStream ms = new MemoryStream();
|
|
|
|
serializer.Serialize(ms, o);
|
|
return Encoding.UTF8.GetString(ms.ToArray());
|
|
}
|
|
|
|
public static object Deserialize(string s, Type t, EncodingType enc = EncodingType.ASCII)
|
|
{
|
|
// the xmlserializer throws and handles an exception. this is normal behavior. microsoft doesn't plan to fix this.
|
|
// http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor
|
|
XmlSerializer deserializer = new XmlSerializer(t);
|
|
byte[] byteArray;
|
|
if (enc == EncodingType.ASCII) byteArray = Encoding.ASCII.GetBytes(s);
|
|
else byteArray = Encoding.UTF8.GetBytes(s);
|
|
|
|
MemoryStream stream = new MemoryStream(byteArray);
|
|
object o = deserializer.Deserialize(stream);
|
|
return o;
|
|
}
|
|
}
|
|
|
|
public enum EncodingType
|
|
{
|
|
ASCII,
|
|
UTF8
|
|
}
|
|
}
|