删除旧的连接字符串

时间:2017-03-02 10:16:17

标签: c# winforms connection-string

我创建了一个可以创建连接字符串并编辑连接字符串的应用程序。

doc.Load(Path.Combine(path, SelectConfigComboBox.SelectedItem.ToString(), "app.config"));
XmlNode xNode = doc.CreateNode(XmlNodeType.Element, "add", "");
XmlAttribute xName = doc.CreateAttribute("name");
XmlAttribute xconnectionString = doc.CreateAttribute("connectionString");
xName.Value = NewKeyTextBox.Text;

xconnectionString.Value = string.Format("data source={0};persist security info={1};initial catalog={2};USER ID={3};password={4}", NewValueTextBox.Text, SecurityInfocomboBox.Text, CatalogcomboBox.Text, UserIDtextBox.Text, PasswordtextBox.Text);

xNode.Attributes.Append(xName);
xNode.Attributes.Append(xconnectionString);
doc.GetElementsByTagName("connectionStrings")[0].InsertAfter(xNode,
doc.GetElementsByTagName("connectionStrings")[0].LastChild);

doc.Save(Path.Combine(path, SelectConfigComboBox.SelectedItem.ToString(), "app.config"));

使用此代码,我输入一个新的connectionString。当我想编辑连接字符串时,它将添加一个新的连接字符串而不删除另一个连接字符串。如何在添加新的之前删除旧的?

2 个答案:

答案 0 :(得分:1)

您可以使用" ConfigurationManager"访问app.config。并更新现有值而不是删除。请参阅以下示例代码:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings["test"].Value = "blah";       
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

答案 1 :(得分:0)

在Visual Studio中转到web.config文件,并将代码放置为 低于

<connectionStrings>
  <add name="ConnectionString" 
       connectionString="Data Source=HP_01\MSSQLSERVER01;Initial Catalog=test;Integrated Security=true;" 
       providerName="System.Data.SqlClient" />
  <add name="testEntities" 
       connectionString="metadata=res:///webservice.csdl|res:///webservice.ssdl|res://*/webservice.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=HP_01\MSSQLSERVER01;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
       providerName="System.Data.EntityClient" />
</connectionStrings>