public class Options
{
public FolderOption FolderOption { set; get; }
public Options()
{
FolderOption = new FolderOption();
}
public void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(Options));
TextWriter textWriter = new StreamWriter(@"C:\Options.xml");
serializer.Serialize(textWriter, this);
textWriter.Close();
}
public void Read()
{
XmlSerializer deserializer = new XmlSerializer(typeof(Options));
TextReader textReader = new StreamReader(@"C:\Options.xml");
//this = (Options)deserializer.Deserialize(textReader);
textReader.Close();
}
}
}
I managed to Save without problem, all members of FolderOption are deserialized. But the problem is how to read it back? The line – //this = (Options)deserializer.Deserialize(textReader); won’t work.
Edit: Any solution to this problem? Can we achieve the same purpose without assigning to this? That is deserialize Options object back into Option. I am lazy to do it property by property. Performing on the highest level would save of lot of effort.
This will work if your Options type is a struct, as you can a alter a struct itself.
If Options is a class (reference type), you can’t assign to the current instance of a reference type with in that instance. Suggesting you to write a helper class, and put your Read and Save methods there, like this
And then consume it from your caller, to read and save objects, instead of trying it from the class.
And put the XmlSerializerHelper in your Util’s namespace, it is reusable and will work with any type.