Skip to main content

How to use a custom config file?

Recently I was wondering how to use custom configuration files in my application. So here it is all about custom configuration file

First of all let me clarify what I mean by custom configuration files?

For me it was simply about using customfile.config instead of the usual app.config and or web.config.


In-order to use customfile.config instead of app.config in an application lets create a simple console application. After you have created a simple console application right click the project in solution explorer window and click add new item. From the list of options available select the Application Configuration File. Now rename the app.config name to customfile.config and click ok. Open the customfile.config.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>




Lets add some configuration elements that are most common to our config files.


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   
<connectionStrings>
       
<add name="SQLCon" connectionString="" providerName=""/>
   
</connectionStrings>

   
<appSettings >
       
<add key="Key1" value="ABC" />
       
<add key="Key2" value="XYZ" />
   
</appSettings >
</configuration>



Now that we have laid our ground work let begin to write code to access this custom config file and its configuration elements. To do this we need to follow the below mentioned steps -

  • Add a reference to System.Configuration.dll

  • Add a using statement on the top to import System.Configuration namespace

  • Now create an object of type ExeConfigurationFileMap and instantiate it using the new keyword

  • This object of type ExeConfigurationFileMap exposes a property called ExeConfigFilename. Assign the name of your custom configuration file to this property

  • Now use the ConfigurationManager to call the method OpenMappedExeConfiguration by passing to it an instance of the above created ExeConfigurationFileMap and a configuration user level enum as ConfigurationUserLevel.None

  • Above call to open a mapped exe configuration will return an instance of Configuration object which you can now use to access your configuration elements as usual.




//create an instance of exe configuration file map type
ExeConfigurationFileMap configFileMap =
new ExeConfigurationFileMap();

//assign the custom config file's name here
configFileMap.ExeConfigFilename = "customfile.config";

//now get an instance of configuration type
// use ConfigurationManager's static method
// OpenMappedExeConfgiuration
Configuration configInstance =
ConfigurationManager.OpenMappedExeConfiguration
(configFileMap, ConfigurationUserLevel.None);

//access appsettings section
configInstance.AppSettings.Settings["Key1"].Value;

//access connection string
configInstance.ConnectionStrings.ConnectionStrings["SQLCon"]
.ConnectionString;


For using this custom config file in a web application the process is absolutely same with the only difference in assigning the filename to ExeConfigFilename property. Here we need to use HTTPContext.Current.Server.MapPath("customfile.config").


//create an instance of exe configuration file map type
ExeConfigurationFileMap configFileMap =
new ExeConfigurationFileMap();

//assign the custom config file's name here
configFileMap.ExeConfigFilename =
HTTPContext.Current.Server.MapPath("customfile.config");

//now get an instance of configuration type
// use ConfigurationManager's static method
// OpenMappedExeConfgiuration
Configuration configInstance =
ConfigurationManager.OpenMappedExeConfiguration
(configFileMap, ConfigurationUserLevel.None);

//access appsettings section
configInstance.AppSettings.Settings["Key1"].Value;

//access connection string
configInstance.ConnectionStrings.ConnectionStrings["SQLCon"]
.ConnectionString;


Comments

Popular posts from this blog

Health Framework - Apple vs Android

In the past few years we have seen mobile and its apps rise and shine transforming many industries in its wake. However, the growth in health and fitness category has been less spectacular at 49% compared to overall mobile app industry which grew at 115% in the year 2013 (source Flurry Analytics). A few years ago Microsoft and Google attempted to make inroads into the health and fitness sector by bringing web based products to store and maintain health and fitness information like MS HealthVault and Google Health with not so spectacular results. Next came innovations by Fitbit in the wearables sector for activity tracking, in 2011 and 2012 they introduced first wireless activity trackers to sync using Bluetooth. This was followed by the entry of Jawbone into health sector with its announcements of Up wristband and accompanying app. These have had better success resulting in many startups joining the wearables product bandwagon.  Late to the stage almos...

Notes on Castle MonoRail

  Sometime back I was doing a small POC on Castle MonoRail. So here are my quick notes on this. MonoRail is an MVC Framework from Castle inspired by ActionPack. MonoRail enforces separation of concerns with Controller handling application flow, models representing data and View taking care of the presentation logic. To work with MonoRail you need Castle Assemblies. It also utilizes nHibernate You can use Castle MonoRail Project Wizard or create the project manually. Project structure – Content Css Images Controllers HomeController.cs Models Views Home \ index.vm Layouts \ Default.vm ...

Quick notes on Git

  I have been away from writing anything for a long time and instead have been fooling around with other stuffs like just plain reading, growing mustache, trying to learn swimming, trying to learn to play acoustic guitar and trying my hands at photography. To be honest I have not given up on them yet but neither have I been able to hang on to them in a disciplined manner. So here I am back to my writing after a long gap. This time its going to be quick notes on Git . Git is a file repository. As opposed to other repositories like SVN Git thinks of its data more like a snapshot of a mini filesystem. All operations in Git are local. (Entire history of the project is stored locally in your working directory) Browsing project history. Viewing all changes to a file. Git uses Checksum to track repository items Everything in Git is check-summed It uses SHA-1 hash for generating check sum values All a...