如何在app.config文件中设置connectionstring值?

时间:2011-05-09 06:54:19

标签: c# .net app-config

我的示例app.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#代码中设置connectionstring值。 我无法更改文件内容。请帮帮我。

2 个答案:

答案 0 :(得分:1)

App.config 代码

      <?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;
    }

答案 1 :(得分:0)

不完全确定这是你应该采取的方法,但无论如何这可能适合你?

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 = "....";
    }
}