Objects to/from XML: generic Load and Save



Hello everyone (and sorry for my English)


I need to store some objects as XML files in order to save data and load it later. I coded this and it works for me:



public static Project Load(String file)
{
using (var stream = System.IO.File.OpenRead(file))
{
var serializer = new XmlSerializer(typeof(Project));
return serializer.Deserialize(stream) as Project;
}
}

public static void Save(Project p, String file)
{
using (var writer = new System.IO.StreamWriter(file))
{
var serializer = new XmlSerializer(p.GetType());
serializer.Serialize(writer, p);
writer.Flush();
}
}


Now, I need to do this with other kind of objects and I don't really want to copy/paste these methods for every object class.


Is possible to pass the object class to methods and make these methods generic for any object class?


Thank you very much in advance!


No comments:

Post a Comment