如何在 app.config 文件中设置连接字符串值

本文关键字:设置 连接 字符串 文件 app config | 更新日期: 2023-09-27 17:55:23

我的示例应用程序.config 文件是

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="DBconn" connectionString="driver={MySQL ODBC 5.1 Driver};server=10.78.17.229;database=grocery;uid=root;pwd=admin;"/>
  </connectionStrings>
</configuration>

我想从 c# 代码设置连接字符串值。我无法更改文件内容。请帮助我。

如何在 app.config 文件中设置连接字符串值

App.cofig Code

      <?xml version="1.0" encoding="utf-8"?>
        <configuration>
     <configSections>
            <section name="dataConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral,        PublicKeyToken=b03f5f7f11d50a3a" />
     </configSections>
    <connectionStrings>
  <add name="DbDatabase" providerName="System.Data.SqlClient" connectionString=""/>
</connectionStrings>

C# 代码

   public void updateConfigFile(string con)
    {
        //updating config file
        XmlDocument XmlDoc = new XmlDocument();
        //Loading the Config file
        XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
       // XmlDoc.Load("App.config");
        foreach (XmlElement xElement in XmlDoc.DocumentElement)
        {
            if (xElement.Name == "connectionStrings")
            {
                //setting the coonection string
                xElement.FirstChild.Attributes[2].Value = con;
            }
        }
        //writing the connection string in config file
        XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        //XmlDoc.Save("App.config");
    }

 private void btn_Connect_Click(object sender, EventArgs e)
    {
        StringBuilder Con = new StringBuilder("Data Source=");
        Con.Append(txt_ServerName.Text);
        Con.Append(";Initial Catalog=");
        Con.Append(txt_DatabaseName.Text);
        if (String.IsNullOrEmpty(txt_UserId.Text) &&String.IsNullOrEmpty(txt_Password.Text))
            Con.Append(";Integrated Security=true;");
        else
        {
            Con.Append(";User Id=");
            Con.Append(txt_UserId.Text);
            Con.Append(";Password=");
            Con.Append(txt_Password.Text);
        }
        string strCon = Con.ToString();
        updateConfigFile(strCon);
        DatabaseTableDA da = new DatabaseTableDA();
        tableList = da.Select_Tables();
        this.lstTables.DataSource = tableList;
    }

不完全确定这是您应该采取的方法,但无论如何这可能对您有用?

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionCollection sections = config.Sections;
foreach (ConfigurationSection section in sections)
{
    ConnectionStringsSection connSettings = section as ConnectionStringsSection;
    if (connSettings != null)
    {
        connSettings.ConnectionStrings[0].ConnectionString = "....";
    }
}