Wednesday, July 8, 2009

Using app.config with Visual C++/CLI

Still on my C++ project with Aculab, I tried putting my application parameters onto a .config XML file just like I normally would with my C# programs. The steps seemed obvious at first -- I added a config file using the templates, then I added a reference to the System.Configuration assembly.

But from inside my code, calling ConfigurationManager::AppSettings does not seem to resolve to anything. I checked the output folder and did not see any application.exe.config that one normally expects from C# projects.

I did a little bit of research and found this app.config article for C++/CLI in CodeProject. It seems that the key is in the project property's post-build event. Specifically, you have to run the external command:
copy app.config "$(TargetPath).config"

This properly copies the config file to the object code output location where it can be read by the application.

The next hurdle is converting the managed System::String^ class, that is returned by the System::Configuration methods, to the old c-style null-terminated string. This one is achieved by using the System::Runtime::Interopservices::Marshal methods. The shortest way of writing this expression that I've seen is this one from MSDN.

No comments: