Question

I would like to create a method that Deserializes a serialized class.

Codes:

Settings newSettings = new Settings(); //Settings is a class.
Settings lastSettings = new Settings();
private void LoadXML(Type type,string filepath)
{
XmlSerializer serializer = new XmlSerializer(type);
FileStream fs = File.Open(filepath,FileMode.Open);
Settings newset = (Settings)serializer.Deserialize(fs); //Deserializes a serializable class file.
newSettings = newset; //Sets these settings as NewSettings
lastSettings = newSettingsXML; //Before form opening, sets information into form.
fs.Close();
}

Now i want to do these with a method. I created also different method for "Person" Class. This method reads person from xml file and sets these person into the form.

private void PersonFromXML(string filepath)
{
XmlSerializer serializer = new XmlSerializer(typeof(BindingList<Person>));
FileStream fs = File.Open(filepath,FileMode.Open);
BindingList<Person> XML_Person = (BindingList<Person>)serializer.Deserialize(fs);
NEW_XML_Person = XML_Person; // These are BindingList<Person>.
fs.Close();
Grid_Person.DataSource = XML_Person;
}

I want to do these Deserializing methods as one different Method. I want to write this method into a dll file. I tried to do these:

private BindingList<Type> FromXML(BindingList<Type> type,string filepath)
{
XmlSerializer ser = new XmlSerializer(typeof(type));
FileStream fs = File.Open(filepath,FileMode.Open);
BindingList<Type> BL = (type)ser.Deserialize(fs);
fs.Close();
return BL;
}

But it did NOT work. Because i could not set BindingList type as Person.. What should I do ? Thanks.

Was it helpful?

Solution

Seems that you forgot to set your generic type parameter on your method declaration.

Try this:

public static class MySerializationHelper
{
   public static class From
   {
      public TReturn XMLFile<TReturn>(string contents)
      {
         var serializer = new XmlSerializer(typeof(TReturn));
         var fs = File.Open(filePath, FileMode.Open);
         var result = (TReturn)serializer.Deserialize(fs);
         fs.Close();
         return result;
      }
   }

   public static class To
   {
      public void XMLFile<TType>(TType object, string filePath)
      {
         // Serialize it here...
      }
   }
}

Than, you may simply use it, like:

var bindingList = MySerializationHelper.From.XmlFile<IBindingList<Person>>("Persons.xml");
var person = MySerializationHelper.From.XmlFile<Person>("Person_1.xml");

MySerializationHelper.To.XmlFile<IBindingList<Person>>(bindingList, "Persons_copy.xml");
MySerializationHelper.To.XmlFile<Person>(person, "Person_1_Copy.xml");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top