Skip to content

Instantly share code, notes, and snippets.

@Geesu
Created December 22, 2019 01:57
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 Geesu/51cc93d5c712d3827e09f972849b07cd to your computer and use it in GitHub Desktop.
Save Geesu/51cc93d5c712d3827e09f972849b07cd to your computer and use it in GitHub Desktop.
public class XmlSerializer
{
// save
public static Boolean Serialize(String Path, object Object)
{
try
{
File.Delete(Path);
}
catch { }
try
{
using (FileStream fs = new FileStream(Path, FileMode.Create))
{
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(Object.GetType());
s.Serialize(fs, Object);
fs.Close();
}
// force clean up!
GC.Collect();
return true;
}
catch (Exception ex)
{
Console.WriteLine("Serialize '{0}' : {1}", Path, ex.ToString());
Console.WriteLine("Inner: {0}", ex.InnerException);
}
return false;
}
// open
public static T DeserializeWithData<T>(String Data)
{
T Result = Activator.CreateInstance<T>();
try
{
StringReader stringWriter = new StringReader(Data);
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(T));
Result = (T)s.Deserialize(stringWriter);
return Result;
}
catch (Exception ex)
{
Console.WriteLine("DeserializeWithData {0}", ex.ToString());
Console.WriteLine(ex.GetBaseException());
}
return Result;
}
// open
public static T Deserialize<T>(String Path)
{
T Result = Activator.CreateInstance<T>();
try
{
if (File.Exists(Path))
{
using (FileStream fs = File.OpenRead(Path))
{
if (fs.Length > 0)
{
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(T));
Result = (T)s.Deserialize(fs);
}
fs.Close();
}
// force clean up!
GC.Collect();
}
return Result;
}
catch (Exception ex)
{
Console.WriteLine("Deserialize '{0}' : {1}", Path, ex.ToString());
Console.WriteLine("Inner: {0}", ex.InnerException);
return Result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment