【问题标题】:Delete the old connectionstring删除旧的连接字符串
【发布时间】:2017-03-02 10:16:17
【问题描述】:

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

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"));

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

【问题讨论】:

    标签: c# winforms connection-string


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,我是否必须在 doc.load 和 doc.save 之间添加此代码?
    • 不行,试试上面的示例代码(没有你的代码),希望对你有帮助。
    • 我已经尝试过你的代码,但是它在每行下面给了我配置的红线找不到类型或命名空间名称“配置”
    • 在你的代码上添加这个:使用 System.Configuration;,你必须导入库
    • 我确定我已经添加了,我已经删除它并再次添加它,但仍然是同样的错误。
    【解决方案2】:

    在 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>
    

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 2021-06-16
      相关资源
      最近更新 更多