Younes abdorah
Younes abdorah

Reputation: 11

Change ConnectionString in run-time in App.config not saved until rebuild a program

I'm using a WinForm form created with C # to connect to a Sql server database.

To connect to the database the user must provide a login and a password.

I use the configuration file App.config to store the connectionString as following :

 <ConnectionStrings>
         <Add name = "K1" connectionString = "Data Source = HP; Initial Catalog = TRVANALYT; User ID = {0}; Password = {1}
       ProviderName = "System.Data.SqlClient" />
 </ ConnectionStrings>  

The problem that is posed to me does not save a new connectionString.
to refresh connextionString K1 I must rebuild the program and it gives the right result If you have suggestions What's the best practice? thank you very much

My Code :

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string connexionstring = ConfigurationManager.ConnectionStrings["K1"].ToString();
var connectionStringsSection = (ConnectionStringsSection) config.GetSection("connectionStrings");
string NewConnexionstring = string.Format(connexionstring, txtUser.Text, txtPwd.Text);
connectionStringsSection.ConnectionStrings["K1"].ConnectionString = NewConnexionstring; //Set new connectionString with user and password
connectionStringsSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("connectionStrings");

App.config

<configSections>
</configSections>
<connectionStrings>
    <add name="K1" connectionString="Data Source=HP;Initial Catalog=TRVANALYT;User ID={0};Password={1}" providerName="System.Data.SqlClient" />
</connectionStrings>

Upvotes: 1

Views: 670

Answers (1)

Duc Tuan
Duc Tuan

Reputation: 11

I have the same problem, but when I debug, I realize that the ConnectionString was saved, but when I create a new object, the Connectionstring of this is false. I fix that by this way:

  • In the Entity.Context.cs file (In my case is QuanLySieuThi.Context.cs) you will see a partial class. You should add a new constructor with a Connectionstring parameter in this class:

Code

 public partial class QuanLySieuThiEntities : DbContext
 {
     //This is the default constructor
     public QuanLySieuThiEntities()
         : base("name=QuanLySieuThiEntities")
     {
     }
     //Add this constructor
     public QuanLySieuThiEntities(String connString)
         : base(connString)
     {
     }
 }
  • Last, when you init a new object, you should use the new constructor with the connectionstring you need:

Code

  string _conString = System.Configuration.ConfigurationManager.ConnectionStrings["QuanLySieuThiEntities"].ConnectionString;
  QuanLySieuThiEntities newObject = new QuanLySieuThiEntities(_conString);

Upvotes: 1

Related Questions