0

I'm trying to test the connection and save the credentials in config file but I keep getting this error " The ConnectionString property has not been initialized"

Here's the C# code

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder str = new StringBuilder("server=");
            str.Append(textBox1.Text);
            str.Append(";database=");
            str.Append(textBox2.Text);
            str.Append(";UID=");
            str.Append(textBox3.Text);
            str.Append(";password=");
            str.Append(textBox4.Text);
            string strcon = str.ToString();
            updateConfigFile(strcon);

            SqlConnection con = new SqlConnection();

            //Refresh Connection String each time else
            //it will use previous connection string.
            ConfigurationManager.RefreshSection("connectionStrings");
            con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;

            //Check the new connection string is working or not
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from egtab3");
            cmd.ExecuteNonQuery();
            MessageBox.Show("Connected Sucessfully");
            con.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public void updateConfigFile(string con)
    {
        //Updating Config File
        XmlDocument xmldoc = new XmlDocument();

        //Loading the Config File
        xmldoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        foreach (XmlElement xElement in xmldoc.DocumentElement)
        {
            if (xElement.Name == "connectionStrings")
            {
                //Setting the connection string
                xElement.FirstChild.Attributes[4].Value = con;
            }
        }
        //writing the connection string in config file
        xmldoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }

and here's the xml code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="con" providerName="using System.Data.SqlClient" 
connectionString=""/>
</connectionStrings>
</configuration>
Varun
  • 1
  • 2
  • In you app.config the connectionstring value is empty, in your code the connectionstring build manually is never used to call the updateConfigFile method (and by the way I don't know if UID is a valid key for Sql Server) So what else do you expect to happen when you try to open the connection? – Steve May 11 '17 at 09:29
  • Thank you . I updated the code. Now i get this error "the index being passed is out of range". what do i do now? – Varun May 11 '17 at 09:43
  • Count the attributes expected in a connectionstring entry. There are three attributes so the correct range for index is 0 to 2 with 2 the one you should use not 4 – Steve May 11 '17 at 09:50
  • Thank you!. That worked. It says connected successfully. Now the thing is the details are not being saved in config file. What do i do now? – Varun May 11 '17 at 10:09
  • How do you know that? – Steve May 11 '17 at 10:11
  • If its about connection, I tried with invalid credentials. It says login failed. Connection is working fine. I checked the app.config file. There is nothing stored in it. – Varun May 11 '17 at 10:43
  • You code doesn't write the app.config but the config file present in the run directory of your program. This file is named after your executable name with the config extension. You will find it in the subfolder BIN\DEBUG (or x86 variant) under your project folder – Steve May 11 '17 at 11:37
  • got it. you're right. It was named same as the exe file. anyways I tried opening it and xml code showed up with no changes. It was empty as before. I tried fiddling around and it throws "Object reference is not set to the instance of an object" exception. – Varun May 11 '17 at 11:52
  • Check ....vshost.exe.config – Steve May 11 '17 at 11:58
  • Done that. No change – Varun May 11 '17 at 12:09
  • Remember that every time you start a new debug session the file app.config is copied back in the BIN\DEBUG folder so the content is reset every time you press F5 to run the app inside vs. What happens if you launch the application standalone? – Steve May 11 '17 at 12:17
  • 2
    Thank you! That did it. the contents are saving in the file when i run it standalone. Thank you for your time. – Varun May 11 '17 at 12:26
  • Glad to be of help. See you again on SO – Steve May 11 '17 at 12:29
  • Firstly, use [SqlConnectionStringBuilder](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=vs.110).aspx) class. Secondly, without admin permissions, your application will not be able to write to the Program Files folder, where your application will be installed at the end user. In any case you must not overwrite the file `app.config`. Save these settings in a different place. – Alexander Petrov May 11 '17 at 14:07

1 Answers1

0

Add update before getting from config

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder str = new StringBuilder("server=");
                str.Append(textBox1.Text);
                str.Append(";database=");
                str.Append(textBox2.Text);
                str.Append(";UID=");
                str.Append(textBox3.Text);
                str.Append(";password=");
                str.Append(textBox4.Text);

                updateConfigFile(str);

                SqlConnection con = new SqlConnection();

                //Refresh Connection String each time else
                //it will use previous connection string.
                ConfigurationManager.RefreshSection("connectionStrings");
                con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;

                //Check the new connection string is working or not
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from egtab3");
                cmd.ExecuteNonQuery();
                MessageBox.Show("Connected Sucessfully");
                con.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
devil_coder
  • 1,115
  • 1
  • 9
  • 12
  • Thank you . I updated the code. Now i get this error "the index being passed is out of range". what do i do now? – Varun May 11 '17 at 09:45
  • I think problem is here xElement.FirstChild.Attributes[4].Value = con; Why did you set to 4? Change index to 2 – devil_coder May 11 '17 at 09:50
  • Thank you!. That worked. It says connected successfully. Now the thing is the details are not being saved in config file. What do i do now? – Varun May 11 '17 at 10:09
  • To update config I would recommend follow this thread http://stackoverflow.com/questions/11149556/app-config-change-value also http://stackoverflow.com/questions/1357240/change-the-value-in-app-config-file-dynamically – devil_coder May 11 '17 at 10:15