Search code examples
c#app-configapplication-settings

Storing database settings outside app.config


I've been writing a c# exe that will be running on a live web server, but I want to be able to test it on our staging server. Since the staging server has different database settings (in the app.config) from my localhost, is there any way I can store the connection string outside the app.config so that I can easily get to it?

Also, is it possible to store the database connection string, then access it via the app.config? This might sound odd, but I'm using a dll from a CMS that uses the value in the .config file.


Solution

  • You can "externalize" any .NET config section into a separate file, and reference it from app.config.

    So in your case, you would have something like this in app.config:

    <connectionStrings configSource="connectionstrings.dev.config" />
    

    and then create separate configs for e.g. DEV, TEST, PROD environments, with different names. Their content would be:

    <?xml version="1.0"?>
    <connectionStrings>
       -- your connection string here, as normal
    </connectionStrings>
    

    You can any any number of those separate files, and switching only means changing a single line in your main app.config to reference the appropriate external connectionstrings.ABC.config file.