0

I have created a form for connection settings, where user can update server name, datatbase and user id and password. I have stored my connection string in app.config file.

My problem is, how can I update connection string in app.config file at run time and How can I change the information of the conectionstring through the text box on the form in the first time, the text box will display information of server name, id, password after the first time

here my app.config

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="Data123.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>   
    </configSections>
  <connectionStrings>
   <add name="Data123Entities" connectionString="metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=nguyenduyhai;initial catalog=Data123;persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <!--<add name="Data123Entities" connectionString="metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=NGUYENDUYHAI\SQLEXPRESS;initial catalog=Data123;persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />-->
  </connectionStrings>
</configuration>

here the code that i am trying but not work , please help me

     void saveconect(string address,string id,string pass)
{

            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
            connectionStringsSection.ConnectionStrings["Data123Entities"].ConnectionString = "data source=" + address + ";initial catalog=" + "Data123" + ";user id=" + id + ";password=" + pass + "";
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
}




 private void buttonUpdate_Click(object sender, EventArgs e)
    {


        saveconect(textboxServerAddress.Text, textBoxUserID.Text, textBoxPassword.Text);
    }
Ng Hà
  • 81
  • 1
  • 1
  • 4
  • Reading from config is easy, writing to them is always a hassle with Configuration Manager namespace. Just use XML directly: http://stackoverflow.com/a/37163251/495455 – Jeremy Thompson Mar 21 '17 at 08:01
  • can you guide me In detail , I'm so grateful if you do – Ng Hà Mar 21 '17 at 11:36
  • Please refer the below link https://stackoverflow.com/questions/502411/change-connection-string-reload-app-config-at-run-time – Ravi Kumar G N Oct 24 '17 at 14:54

2 Answers2

0

Have you tried to run application in release folder? Because in Debug mode won't change.

  • of course i run it in release folder but still didn't work , do you thinks my code has mistake ? – Ng Hà Mar 21 '17 at 11:33
0

With using System.Xml.Linq; it will be something like:

var doc = XElement.Load(fileName); 
var target = doc.Element("configuration").Elements("configurationStrings").Where(e => e.Element("name").Value == "Data123Entities").Single(); 
target.Element("connectionString").Value = "metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=" + dataSource + ";initial catalog=" + initCatalog + ";persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework&quot;"
doc.Save(fileName);
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • my filename = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile but i got this , what shoud i do System.NullReferenceException was unhandled Message: An unhandled exception of type 'System.NullReferenceException' occurred in ShinEtsu.exe Additional information: Object reference not set to an instance of an object. – Ng Hà Mar 22 '17 at 03:04
  • *Object reference not set to an instance of an object.* is the most popular .net error message... I'm sorry but you have to google your way through that to resolve it... its too easy - step through the code until you get the exception and look what object is null on the line it fails!!! – Jeremy Thompson Mar 22 '17 at 03:09
  • one last question you give me this var target = doc.Element("configuration").Elements("configurationStrings").Where(e => e.Element("name").Value == "Data123Entities").Single(); but i don't see any "configurationStrings" part in my app.config above was it wrong or I'm missing something ? – Ng Hà Mar 22 '17 at 03:22