Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone,

Please how do i dynamically set connectionstring in app.config file using user inputs,

i have tried this:
C#
                StringBuilder Con = new StringBuilder( "Data Source=" );
                Con.Append( txtServer.Text );
                Con.Append( ";Initial Catalog=" );
                Con.Append( txtDatabase.Text );
                if ( String.IsNullOrEmpty( txtUsername.Text ) &&          String.IsNullOrEmpty( txtPassword.Text ) )
                    Con.Append( ";Integrated Security=true;" );
                else
                {
                    Con.Append( ";User Id=" );
                    Con.Append( txtUsername.Text );
                    Con.Append( ";Password=" );
                    Con.Append( txtPassword.Text );
                }
                string strCon = Con.ToString( );
                updateConfigFile( strCon );

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


It doesn't seem to give the desired result, Please any assistance will be appreciated.
Posted

1 solution

see here[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900