Zeus82
Zeus82

Reputation: 6375

How to Override a Value in Web.config Programatically

I am developing a web app with a group of people and we all have different connection strings to our database.

The connection string is stored in our web.config which is source controlled, and sometimes people check in their web.config with their connection string which messes up my environment.

I want to use an environment variable that if exists will override the connection string in my web.config. How can I do that?

Upvotes: 0

Views: 1215

Answers (2)

Jim B
Jim B

Reputation: 8574

Is it possible for you to move your connection strings from your application-level web.config down to your system-level machine.config file?

Upvotes: 0

Belogix
Belogix

Reputation: 8147

As others have noted in your comments there is no easy way to stop people from changing any file that is under source-control. However, what you could do is change your web.config file to have:

<connectionStrings configSource="Configs\ConnectionStrings.config" > </connectionStrings>

Then have a folder called Configs and in there a file named ConnectionStrings.config with content like:

<connectionStrings>
  <add name="YourVersionHere" ... />
</connectionStrings>

That way you can check the web.config file in / out without it altering your connection string (it is now held in a separate file). Of course, this doesn't get you out of jail because they can then overwrite the ConnectionStrings.config file but it does allow you to break your config out so you can always be up to date with all the settings but never do a GET on your ConnectionStrings.config file.

The same applies to AppConfig etc. Basically allows you to manage your config in smaller chunks rather than all in one place.

You can get more information here: http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx

Upvotes: 2

Related Questions