Translate

Thursday, August 9, 2012

How to read from a config file within the project

By default the config file an application reads is the config file in the project that has the entry point.  For instance if you have a console application that references a project A. And if project A has a config file. When you run the app, you will notice that even if you put settings in the config file, when you try to read, it always comes out as null. The reason is the application tries to read from a config file from the project that has the main method (entry point to the app).

The code below will help you read from the config file from within the project.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
 
namespace ClassLibrary1
{
    public class Class1
    {
 
        public static string ConfigRead(string locOfConfig)
        {
 
            //eg   locOfConfig =@"C:\SandBox\ConsoleApplication2\ClassLibrary1\App.config";
 
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = locOfConfig;
 
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
 
            string x = config.AppSettings.Settings["test"].Value;
 
            return x;
        }
    }
 
 
}

 
 
}


Don't forget to add a reference to the System.Configuration dll within your project

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator