views:

55

answers:

2

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

+1  A: 

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).

GôTô
Good answer. There's a bit more, though.. Permissions need to be set properly. This article covers that as well: http://odetocode.com/Articles/418.aspx
David Stratton
@David Stratton: You are right, permissions should be properly set. I will update my answer taking this into account, thank you.
GôTô
+1  A: 
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!

Mouhannad
Thanks - one change I had to make to the code above is on line 3: `myConfiguration.ConnectionStrings.ConnectionStrings["xxxconnection"].ConnectionString = "yyy";`
Jimbo
thanks for pointing that out, so did it work for you?
Mouhannad
It did, just waiting until im allowed to accept the answer :)
Jimbo
im glad its solved!
Mouhannad