Edit Connection String in code and save into web.config
I am building an installer for my CMS, AdvGenCMS. The first part is adding connection string and saves it into web.config. That is doable in C#. Just like the following code:
Code
Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); | |
ConnectionStringsSection connectionStrSection = config.GetSection("connectionStrings") as ConnectionStringsSection; | |
string conntectStr = String.Format("data source={0};Initial Catalog={1};uid={2};password={3};Intergrated Security=SSPI",serverModel.ServerName,serverModel.DatabaseName,serverModel.UserName,serverModel.UserPassword); | |
if (connectionStrSection != null) | |
{ | |
if ( connectionStrSection.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"] == null) | |
{ | |
ConnectionStringSettings setting = new ConnectionStringSettings(); | |
setting.Name = "AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"; | |
connectionStrSection.ConnectionStrings.Add( | |
setting); | |
} | |
connectionStrSection.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"].ConnectionString = conntectStr; | |
connectionStrSection.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"].ProviderName = "System.Data.SqlClient"; | |
config.Save(); | |
} |
We can use WebConfigurationManager.OpenWebConfiguration("~") to get the whole configuration and then use config.GetSection("connectionStrings") to get the connection string section. Now, we can play around the connection string section freely.
Trackback address for this post
Trackback URL (right click and copy shortcut/link location)
No feedback yet
Form is loading...