Modify the connection line at App.config



  • So I get the line of the line of the compound that's introduced by the laser:

    DataConnectionDialog dcd = new DataConnectionDialog();
    DataConnectionConfiguration dcs = new DataConnectionConfiguration(null);
    dcs.LoadConfiguration(dcd);
    

    if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
    {
    using (SqlConnection connection = new SqlConnection(dcd.ConnectionString))
    {
    //..
    }
    }

    dcs.SaveConfiguration(dcd);

    How do you make the whole program work with that line?



  • Keep the line of connection to the OBD in the configuration file app.config

    <connectionStrings>
        <add name="MyConnectionString" providerName="System.Data.SqlClient" connectionString="data source=sqlserver;Initial Catalog=BD;User Id=user;Password=password" />
    </connectionStrings>
    

    From app.config, you can read it easily by class. ConfigurationManagerany section of the code

    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    

    If you want to replace her in runtime, do that.

        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");         
        connectionStringsSection.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=serverChange;Initial Catalog=BDD;user=user1;password=password";
        config.Save();
        ConfigurationManager.RefreshSection("connectionStrings");
    

    If you try to read the line of connection again, you'll get a modified line of connection.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2