在C#中运行时更新app.config文件中的connectionstring

时间:2012-07-25 07:34:17

标签: c# connection-string

我已经创建了一个应用程序,并且该应用程序将在数据库中插入,更新和删除数据操作

我还创建了一个连接设置表单,用户可以在其中更新服务器名称,数据库以及用户ID和密码。我已将连接字符串存储在app.config文件中。

我的问题是,如何在运行时更新app.config文件中的连接字符串?

6 个答案:

答案 0 :(得分:1)

你可以试试这个:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("MyConnectionString",String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}","testing", "testing2", "Testing6")));
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

答案 1 :(得分:0)

你可以试试这个:

private void changeValue(String KeyName, String KeyValue)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Update the setting.
config.AppSettings.Settings[KeyName].Value = KeyValue;

// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);

// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}

答案 2 :(得分:0)

我相信你的App.Config没有更新,因为它正在使用vshost。我今天遇到了这个问题,我尝试了这篇文章的解决方案,但在VisualStudio上运行,所以文件是一样的。在VS之外,它充当了魅力。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
 connectionStringsSection.ConnectionStrings["ClientCN"].ConnectionString = "server=localhost;user=root;port=3306;password=abc";
 config.Save();
  ConfigurationManager.RefreshSection("connectionStrings");

答案 5 :(得分:0)

试试这个:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["ClientCN"].ConnectionString = "server=localhost;user=root;port=3306;password=abc";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");