Hi, guys. I use XMLSerializer to keep and restore program options. Here is the code:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace XMLAsk
{
class Test
{
public static string ConfigFileName = "C:\\Work\\TMP\\Config.xml";
public static void Main()
{
MyOptions myOptions = new MyOptions();
myOptions.Title = "Hello, world!";
myOptions.Rating = 15;
SerializeToXML(myOptions);
MyOptions myOptions2 = new MyOptions();
DeserializeFromXML(myOptions2);
MessageBox.Show(myOptions2.Title);
}
public static void SerializeToXML(MyOptions myOptions)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyOptions));
TextWriter textWriter = new StreamWriter(ConfigFileName);
serializer.Serialize(textWriter, myOptions);
textWriter.Close();
}
public static void DeserializeFromXML(MyOptions myOptions2)
{
XmlSerializer deserializer = new XmlSerializer(typeof(MyOptions));
TextReader textReader = new StreamReader(ConfigFileName);
myOptions2 = (MyOptions)deserializer.Deserialize(textReader);
textReader.Close();
}
}
public class MyOptions
{
private string title;
private int rating;
public string Title
{
get { return title; }
set { title = value; }
}
public int Rating
{
get { return rating; }
set { rating = value;}
}
}
}
Serialization does work. I get the following xml-file (Config.xml):
<?xml version="1.0" encoding="utf-8" ?>
- <MyOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Title>Hello, world!</Title>
<Rating>15</Rating>
</MyOptions>
But deserialization seems doesn't work. For instance, when I display one of options with MessageBox.Show(myOptions2.Title); (see code above), then I get an empty string.
Why? What's wrong with my code?