Mar 29, 2013

multiple config in c#

Introduction When building a console app, it is often necessary to provide various settings. Adding an app.config file to your project allows you to store all your settings in a file that is processed at runtime. When compiled, app.config becomes yourapp.exe.config. This is great until you need to run a large collection of different settings depending on the circumstance. There are a few ways I have seen to deal with this: Create a number of config files with the correct keys and before runtime, name the config file you want to use as yourapp.exe.config. Workable, but since you are always renaming files, it may become difficult to determine which settings have been run and which have not. Create custom tags in the app.config (see simple two-dimensional configuration file), then via another key set which section is the setting you want during the current run. This is the solution I have seen a number of times on the Internet. This is a workable solution, but it can lead to unwieldy app.config files, depending on the number of keys and configurations. I was not satisfied with both of these solutions. What I wanted was the ability to specify at runtime which config file to use. In this way, I can keep settings for different configurations neatly separated. Here is how I did this. A Console App Collapse | Copy Code using System; using System.Configuration; using System.Collections.Generic; using System.IO; using System.Text; using System.Data; using System.Data.SqlClient; using System.Net; namespace yournamepace { class Program { static void Main(string[] args) { // get config file from runtime args // or if none provided, request config // via console setConfigFileAtRuntime(args); // Rest of your console app } } protected static void setConfigFileAtRuntime(string[] args) { string runtimeconfigfile; if (args.Length == 0) { Console.WriteLine("Please specify a config file:"); Console.Write("> "); // prompt runtimeconfigfile = Console.ReadLine(); } else { runtimeconfigfile = args[0]; } // Specify config settings at runtime. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.File = runtimeconfigfile; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } } app.config Collapse | Copy Code Typical Runtime Config File 1 Collapse | Copy Code Typical Runtime Config File 2 Collapse | Copy Code Now, at runtime, you do the following from the command prompt: Collapse | Copy Code c:\> yourapp.exe myruntimeconfigfile1.config c:\> yourapp.exe myruntimeconfigfile2.config Or just double click yourapp.exe, and you will be prompted for a config file. original post http://www.codeproject.com/Articles/14465/Specify-a-Configuration-File-at-Runtime-for-a-C-Co