Changer la connection string d'une autre application avec XML

Tags : connectionString

Categories: ASP MVC, C#

Comment changer la conenction string d'une autre application avec XML.

A utiliser SEULEMENT pour ce cas, sinon utiliser les méthodes habituelles avec configuration manager.

 

private bool ChangeConnectionString(string connStringName, string newValue, string path)
{
try
{
//CreateXDocument and load configuration file
XDocument doc = XDocument.Load(path + "/web.config");
//Find all connection strings
var query1 = from p in doc.Descendants("connectionStrings").Descendants()
                             select p;
 
//Go throught each connection string elements find atribute specified by argument and replace its value with newVAlue
foreach (var child in query1)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == connStringName)
 
 if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
 
atr.NextAttribute.Value = newValue;
}
}

doc.Save(path + "/web.config");
return true;
}
catch (Exception ex)
{
lblError.Text += "Error to change the web.config with this value " + newValue + " and this path " + path + "<br/> " + ex.Message;
return false;
       }
}

Aucun commentaire

Ajouter un commentaire