I have an XML file that contains database settings that may change depending on where it is read. Preferably, I would read those settings from some configuration file. How can this be done?
A:
You can either use the app.config file, or create your own XML file to store them
Tim
2009-06-03 14:03:42
+1
A:
You can use the System.Xml.Serialization.XmlSerializer class to automatically pull the settings into a custom class.
Create a class with your settings:
public class Settings
{
private string connectionString;
public string ConnectionString
{
get { return connectionString; }
set { connectionString = value; }
}
}
Then use the following to pickup data:
Settings settings = new Settings();
FileStream filestream = new FileStream("settings.xml", FileMode.Open);
System.Xml.Serialization.XmlSerializer cereals = new System.Xml.Serialization.XmlSerializer(typeof(Settings));
settings = cereals.Deserialize(filestream);
Likewise, if you want to assign the current object to the settings file, do this:
XmlSerializer cereals = new XmlSerializer(typeof(Settings));
System.IO.FileStream writer = new FileStream("settings.xml", FileMode.Create);
cereals.Serialize(writer, settings);
In this case the "settings.xml" file is in the current directory, but I normally put it in the User's app data folder, because you can always write to that.
Dave Arkell
2009-06-03 14:13:39
One of the things to remember with the XMLSerializer is that it can't serialize Dictionary<> objects. However, you can write your own XMLSerialization methods by implementing the IXmlSerializable interface.
Navaar
2009-06-03 14:16:51
A:
Try my following post on this subject, very similar to the proposed solution by Dave above but just with a bit more flesh. http://www.picnet.com.au/blogs/Guido/post/2009/09/10/XML-Settings-Files-No-more-webconfig.aspx
gatapia
2009-09-09 22:42:38