简体   繁体   English

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

[英]update connectionstring in app.config file at run time in C#

I have created an application and in that application am going to insert, update and delete data operation in database 我已经创建了一个应用程序,并在该应用程序中将插入,更新和删除数据库中的数据操作

I have also created a form for connection settings, where user can update server name, datatbase and user id and password. 我还创建了一个连接设置表单,用户可以在其中更新服务器名称,数据库以及用户ID和密码。 I have stored my connection string in app.config file. 我已将我的连接字符串存储在app.config文件中。

My problem is, how can I update connection string in app.config file at run time? 我的问题是,如何在运行时更新app.config文件中的连接字符串?

You can try this: 你可以试试这个:

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

You can try this: 你可以试试这个:

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

I believe that your App.Config is not updating because it is using the vshost. 我相信你的App.Config没有更新,因为它正在使用vshost。 I had this issue today, and I tried the solutions of this post, but running on VisualStudio, so the file was the same. 我今天遇到了这个问题,我尝试了这篇文章的解决方案,但在VisualStudio上运行,所以文件是一样的。 Outside VS it worked as a charm. 在VS之外,它充当了魅力。

App.cofig Code App.cofig代码

      <?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# Code 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;
    }
 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");

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#中运行时读取,写入和更新app.config文件中的连接字符串 - read,write and update connectionstring in app.config file at run time in C# c# - 在运行时更改 App.Config 后实体框架 ConnectionString 不会更新 - c# - Entity Framework ConnectionString won't update after changing App.Config in runtime app.config 上的 C# ConnectionString 在其他计算机上不起作用 - C# ConnectionString on app.config not working on other computers 是否有可能(以及如何)在C#中在运行时将ConnectionString添加到app.config? - Is it possible (and how) to add ConnectionString to app.config at runtime in C#? C#使用appSettings参数在app.config中撰写connectionString - C# compose connectionString in app.config using appSettings parameters 如何将连接字符串从 App.config 移动到 C# 中的代码? - How to move connectionString from App.config to code in C#? C#运行另一个程序并指定App.Config文件 - C# Run Another Program and Specify App.Config File 使用C#在安装时修改App.Config文件 - Modifying App.Config file at the time of installation using c# 如何在app.config文件中操作connectionstring? - how to manipulate connectionstring in app.config file? 如何在C#中更新app.config - How to update app.config in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM