I have a problem with programmatically change connection string in the app.config file.
In overriden OnStart method I want to change app.config file(only connection string)
At this moment I have this:
private static void ChangeConnectionString(string newDatasource)
{
try
{
XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var query = from p in doc.Descendants("connectionStrings").Descendants()
select p;
foreach (var child in query)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == "UniversityEntities" &&
atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
{
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
connectionStringBuilder.DataSource = newDatasource;
connectionStringBuilder.InitialCatalog = "UniversityDB";
connectionStringBuilder.IntegratedSecurity = true;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(atr.NextAttribute.Value);
entityBuilder.ProviderConnectionString = connectionStringBuilder.ToString();
atr.NextAttribute.Value = entityBuilder.ToString();
}
}
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("connectionString");
}
catch (Exception x)
{
}
}
if you want to create a UI to modify the config you can do that. but it wouldn’t happen within the application itself.
1st you have the service/app that will be affected.
2nd you have another app that will change the file.
when the admin clicks “change connection string” from the 2nd app, the 2nd app will stop the 1st service/app. change the connection string. start the 1st service/app.
so from the perspective of the 1st app it won’t have to think about hacking together a connection string.
————————————–
an alternative is to remove the connection string for the config file altogether and simply make the connection string a required parameter when the application starts. so if it’s a server it might look like this
net start [name of service] “the connection string…”
from the 2nd UI you could just overwrite a bat/ps script that starts/stops the service. this way you don’t have to hack through the xml of the app.config file.
————————————–
one last comment. remove the try/catch, it’s completely useless and you need to know if there are problems when changing the file.