views:

1534

answers:

13
  • You can use App.config; but it only supports key/value pairs.
  • You can use .Net configuration, configuration sections; but it can be really complex.
  • You can use Xml Serialization/Deserialization by yourself; your classes-your way.
  • You can use some other method; what can they be? ...

Which of these or other methods (if there are) do you prefer? Why?

+12  A: 

If I can get away with it I will just use the App.Config, however, if I need something more complex I will use custom configuration sections. Yes it is a pain to get an understanding of in the beginning, but a unified configuration source, and familiar configuration for all settings is worth the time investment in my opinion.

Mitchel Sellers
The other advantage to using App.Config is that it is the framework-supported method of configuring your app. This gives you advantages such as tutorials, API docs, external help etc. etc.
Aydsman
A: 

I keep most of my config in IoC container, e.g. Spring.Net.

Matt Howells
+1  A: 

I use a custom xml configuration file, where a different config file is used for each environment (dev/qa/prod). The config files are templates that are dynamically instantiated with things like host/port configurations for services - this makes multi environments and failover very easy as it can be handled by the template instantiation code.

Of course if you have very little config and are not concerned with multiple environments then app.config is more standard and is probably the best way to go.

Chris
A: 

I find NameValueCollectionHandler the easiest and best, and I generally would link off to an external config file via the configSource attribute.

I try to put the ABSOLUTE MINIMUM configuration in config files, with most of it being configured in code with an Application that is self-aware of its deployment environment (such as by machine name or IP Address if known). Of course this required much more pre-planning and knowledge of your environments, but much less headache when deploying.

Xian
+2  A: 

I was a network/system admin in the past, and now I develop internal utilities for database applications. What I've found is this:

Simple Non-Nested configuration files are the best for applications that won't be changing where they access their resources very much.

Anything more complex needs to go into a database with an administration UI. This only applies to regular business users. If you are worried about the database getting corrupted, then use the complex configuration file approach. Files tend to corrupt less than databases.

Now, if your users are other developers, then you will have a lot more flexibility on what to use to store your configurations.

hectorsosajr
A: 

If you have .NET 3.0 available, I find the XamlReader/XamlWriter very handy for storing settings. They can write/read any .NET object to XAML if:

  • The object has a parameterless constructor
  • The properties to read/write have public getters and setters

It is especially nice that you don't have to decorate your settings objects with any attributes.

Abe Heidebrecht
+18  A: 

When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section):

Define your custom section:

        public class CustomSection : ConfigurationSection
        {
            [ConfigurationProperty("LastName", IsRequired = true,
            DefaultValue = "TEST")]
            public String LastName
            {
                get { return (String)base["LastName"]; }
                set { base["LastName"] = value; }
            }

            [ConfigurationProperty("FirstName", IsRequired = true, DefaultValue =
            "TEST")]
            public String FirstName
            {
                get { return (String)base["FirstName"]; }
                set { base["FirstName"] = value; }
            }

            public CustomSection()
            {

            }
        }

Programmatically create your section (if it doesn't already exist):

           // Create a custom section.
            static void CreateSection()
            {
                try
                {

                    CustomSection customSection;

                    // Get the current configuration file.
                    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe");

                    // Create the section entry  
                    // in the <configSections> and the 
                    // related target section in <configuration>.
                    if (config.Sections["CustomSection"] == null)
                    {
                        customSection = new CustomSection();
                        config.Sections.Add("CustomSection", customSection);
                        customSection.SectionInformation.ForceSave = true;
                        config.Save(ConfigurationSaveMode.Full);
                    }
                }
                catch (ConfigurationErrorsException err)
                {
                    //manage exception - give feedback or whatever
                }

            }

Following CustomSection definition and actual CustomSection will be created for you:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" />
  </configSections>
  <CustomSection LastName="TEST" FirstName="TEST" />
</configuration>

Now Retrieve your section properties:

    CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection");
    string lastName = section.LastName;
    string firstName = section.FirstName;
JohnIdol
A: 

dataset.WriteXML()/dataset.ReadXML() work pretty well for me when the app.config doesn't cut it anymore.

Joel Coehoorn
+2  A: 

Put your configuration into a database. If you run your app on more than 1 machine (eg a client-server app) then all the per-machine config systems are a PITA. A single config area is the best way to place your configuration. Write a gui to manage it and you'll be very happy.

Rolling out app.config files to 200 client boxes.. its not fun, especially when one gets missed (and they do, believe me).

gbjbaanb
A: 

Mostly I prefer using custom xml file and Xml Serialization method to read and write this config files... Not restricted to key/value pairs and not complex to implement...

spinodal
A: 

I've had good luck rolling my own special class that returns config data from a ".settings" file associated with the calling assembly. The file is XML, and the settings class exposes it publicly as an XDocument. Additionally, the indexer for this settings class returns element values from /settings/setting nodes.

Works great for simple applications where you just need a key/value pair access to settings, and works great for complicated settings where you need to define your own structure and use System.Xml.Linq to query the XML document.

Another benefit of rolling your own is that you can use FileSystemWatcher and callback Action type to automatically fire a method when the file changes at runtime.

Chris
+1  A: 

I thing key/value configurations work pretty well for simple configurations files. It becomes a problem when the file starts to grow and difficult to maintain. We started to split configuration file to "common" and "specific" applications configurations. The file access is transparent to app, "common" values are the same in most cases, but "specific" differ for every deployed application.

Valery
A: 

I use a custom xml config file. Each setting has a key, value and type.

It has one main section that contains all settings and additional sections containing setting overrides for particular environments (dev, staging, live). This i don't need to replace sections of the file when deploying. I have a small wrapper which you can call to get a particular setting or a dictionary containing all of them.

I recently created a T4 template that will read the config file and create a static strongly typed settings class. That's been a huge timesaver.

marto