我有在app.config中更改连接字符串的代码。但是当我更改数据库时遇到错误,因为linq to sql.dbml没有更新到我改变的数据库。 我需要关闭程序并再次打开以实现更改。我该怎么做才能将我的linq更新为sql.dbml?
var name = "DbName";
bool isNew = false;
string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
XmlNode node;
isNew = list.Count == 0;
if (isNew)
{
node = doc.CreateNode(XmlNodeType.Element, "add", null);
XmlAttribute attribute = doc.CreateAttribute("name");
attribute.Value = name;
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("connectionString");
attribute.Value = "";
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("providerName");
attribute.Value = "System.Data.SqlClient";
node.Attributes.Append(attribute);
}
else
{
node = list[0];
}
string conString = node.Attributes["connectionString"].Value;
SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
conStringBuilder.DataSource = txtConnectServername.Text;
conStringBuilder.InitialCatalog = "AlTayerDB";
conStringBuilder.PersistSecurityInfo = true;
conStringBuilder.UserID = txtConnectUserId.Text;
conStringBuilder.Password = txtConnectAdapterPassword.Text;
conStringBuilder.MultipleActiveResultSets = true;
node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
if (isNew)
{
doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
}
doc.Save(path);
答案 0 :(得分:0)
我建议您按照此处 - How do I (update/insert/remove) the config file during runtime?获取有关此主题的完整信息:
在运行时修改配置文件中的现有值。
由于Configuration.AppSettings属性是只读的,为了修改当前的应用程序设置值,我们必须使用XmlDocument类将应用程序配置文件直接更新为XML文档。
这是原始的App.config文件:
<configuration>
<appSettings>
<add key="Setting1" value="1" />
<add key="Setting2" value="2" />
</appSettings>
</configuration>
以下是修改应用程序设置值的代码示例:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement element in xmlDoc.DocumentElement)
{
if (element.Name.Equals("appSettings"))
{
foreach (XmlNode node in element.ChildNodes)
{
if (node.Attributes[0].Value.Equals("Setting1"))
{
node.Attributes[1].Value = "New Value";
}
}
}
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");
如果这不符合要求,请检查以下参考文献:
Change the value in app.config file dynamically
App.Config change value
update app.config file programatically with ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);