views:

158

answers:

3

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

http://stackoverflow.com/questions/114527/simplest-way-to-have-a-configuration-file-in-a-windows-forms-c-application

Tim
+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
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
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