2

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?

echoblaze
  • 11,176
  • 13
  • 44
  • 49

3 Answers3

1

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
  • 3,920
  • 2
  • 22
  • 27
  • 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 Jun 03 '09 at 14:16
0

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
  • 3,574
  • 4
  • 40
  • 48
0

You can either use the app.config file, or create your own XML file to store them

Simplest way to have a configuration file in a Windows Forms C# Application

Community
  • 1
  • 1
Tim
  • 7,746
  • 3
  • 49
  • 83