Jimbo
Jimbo

Reputation: 23004

Changing your web.config from your ASP.NET application

I need to change the database connection string in the web.config file but havent got a clue how to go about this. Does anyone have any experience with that?

UPDATE
Sorry, not very clear above, I want to be able to change a connection string from the web application after it has been deployed

Upvotes: 4

Views: 258

Answers (2)

Mouhannad
Mouhannad

Reputation: 2209

Configuration myConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
//appSettings configuration
myConfiguration.AppSettings.Settings["xxx"].Value = "yyy";
//database connections configuration
myConfiguration.ConnectionStrings.ConnectionStrings["xxxconnection"].ConnectionString = "yyy";
myConfiguration.Save();

http://msdn.microsoft.com/en-us/library/system.configuration.configuration.connectionstrings.aspx

Edit:

http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringssection.aspx

Also, as pointed out by the others, you need to set the correct permissions but sometimes using shared hosting (from experience) they ask you for the username and password of your account and once you enter that, your web.config is changed. So try it and if it doesn't work and you don't have access to set the permissions then I'm afraid you have to look into something else.

Good luck!

Upvotes: 2

GôTô
GôTô

Reputation: 8053

Use the WebConfigurationManager class as shown here.

As it is very sensitive information, proper permissions need to be set as explained on this site (link proposed by David Stratton).

Upvotes: 1

Related Questions