using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
namespace Veasel.Serialisierung
{
public enum SerialisierungTyp
{
Binary,
XML
}
public class Serialisierung<T>
{
FileStream fs = null;
#region öffentliche Methoden
public void SaveToFile(T objectToSave, string FileName, SerialisierungTyp typ)
{
switch (typ)
{
case SerialisierungTyp.Binary: SaveBinary(objectToSave, FileName);
break;
case SerialisierungTyp.XML: SaveXML(objectToSave, FileName);
break;
default:
break;
}
}
public T LoadFromFile(string FileName, SerialisierungTyp typ)
{
T serializedObject = default(T);
switch (typ)
{
case SerialisierungTyp.Binary: serializedObject = LoadBinary(FileName, serializedObject);
break;
case SerialisierungTyp.XML: serializedObject = LoadXML(serializedObject, FileName);
break;
default:
break;
}
return serializedObject;
}
#endregion
#region private Methoden
#region Binary
private void SaveBinary(T obj, string filename)
{
try
{
fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, obj);
}
finally
{
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
}
private T LoadBinary(string filename, T obj)
{
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
obj = (T)bf.Deserialize(fs);
}
finally
{
fs.Flush();
fs.Close();
}
return obj;
}
#endregion
#region XML
private void SaveXML(T obj, string filename)
{
try
{
fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
XmlSerializer bf = new XmlSerializer(typeof(T));
bf.Serialize(fs, obj);
}
finally
{
if (fs != null)
{
fs.Flush();
fs.Close();
}
}
}
private T LoadXML(T obj, string filename)
{
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
XmlSerializer bf = new XmlSerializer(typeof(T));
obj = (T)bf.Deserialize(fs);
}
finally
{
fs.Flush();
fs.Close();
}
return obj;
}
#endregion
#endregion
}
}