Using application configuration file (app.config) with C++/CLI applications

.NET applications uses app.config file to keep the application configuration entries like database connection strings, logging information etc.  Using Visual Studio, you can add a new app.config file to your application. In C# and VB.NET projects, app.config will be copied automatically to the output directory and it will be named like <Application>.exe.config where <Application> is your executable name. ConfigurationManager is a helper class which provides a neat interface to the contents of app.config.

With the above information, let us write a simple application which reads AppSettings node from the application configuration file.

System::Void FancyForm::Load(System::Object^  sender, System::EventArgs^  e)
{
      using namespace System::Configuration;
      String^ logFileName = ConfigurationManager::AppSettings["log_file"];
}

Code looks pretty straightforward, but you will get an empty string when you execute this. In C# or VB.NET, Visual Studio will copy the app.config file when you build the project. For C++/CLI, VS is not doing this. ConfigurationManager class will look for the app.config file in the output directory.

We can make some changes to project settings for forcing visual studio to copy the file when building. Try the following steps

  1. Right click on the app.config file in Solution Explorer and choose Properties.
  2. Make sure Exclude from build is set to NO.
  3. Tool is set to Custom Build Tool.
  4. Click on the Custom Build Step.
    1. Set the Command line to type app.config > “$(TargetPath).config”. $(TargetPath) will have the output path where VS is building the output files.
    2. Set description to Updating target’s configuration file.
    3. Set outputs to (TargetPath).config.

You are done! Now try to build the project and you can see that VS copies the app.config to output directory. Following screen shot shows the settings in my system.

app.config settings screen for allowing copying to output directory

app.config settings screen for allowing copying to output directory

BTW, I wonder why VS is not doing this automatically.

Happy programming!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s