Search code examples
c#.netapp-configconfigurationmanager

Open other program's configuration files


I have a program A, it also have an app.config file where I have added some keys like server address, username and password for connecting to a server. It is a console application. Now I want to make a UI which I have done. In that UI I want to modify the content of app.config of program A. How do I do that?

Here is what I tried, I copied the UI (basically an .exe) to program A's directory, where the app.config also resides. Then in the UI, I use the ConfigurationManager class's OpenExeConfiguration method, and passing the program A's filename as an argument. But it throws and exception of type System.Configuration.ConfigurationErrorsException.

So I think that my approach is incorrect. How shall I do this?

EDIT: Oh I forgot to tell I'm using C#, .NET 3.5 and VS 2008 (if that helps :D)


Solution

  • I'm not sure about the problem with your approach (try adding the stack trace to your post) but this is how I do it:

    var configMap = 
        new ExeConfigurationFileMap
        {
            ExeConfigFilename = externalConfigurationFile
        };
    System.Configuration.Configuration externalConfiguration =
        ConfigurationManager.OpenMappedExeConfiguration(
            configMap,
            ConfigurationUserLevel.None);
    
    foreach (var setting in externalConfiguration.AppSettings.Settings)
    {
        ...
    }
    
    externalConfiguration.Save(ConfigurationSaveMode.Full);