0

I am trying to update the app.config file at runtime. I get the error

System.NullReferenceException: object reference not set to an instance of an object. line 59.

What I am trying to do is change the url at runtime, by having a pop up form which has a textbox which is used for the url, this is then used to update the config file.

public void changeSettings()
    {
        Configuration config =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection settings = config.AppSettings.Settings;

        try
        {
            Console.WriteLine("nothing " + ConfigurationManager.AppSettings["client_postCodeRef_Service"]);
            settings["client_postCodeRef_Service"].Value = textBox1.Text; <- line 59
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("applicationSettings");
            Console.WriteLine("nothing 2 " + ConfigurationManager.AppSettings["client_postCodeRef_Service"]);
        }
        catch (ConfigurationErrorsException e)
        {
            MessageBox.Show("[Exception error: {0}]",
                e.ToString());
        }




    }

here is the config file

 <applicationSettings >
    <Client.Properties.Settings>
      <setting name="client_postCodeRef_Service" serializeAs="String">
        <value>http://127.0.0.1/directory/directory/webService.asmx</value>
      </setting>
      </Client.Properties.Settings>
    </applicationSettings>
Jed I
  • 998
  • 3
  • 19
  • 37
  • Dumb question...Have you got a "client_postCodeRef_Service" key in your appSettings collection? If not, accessing its Value property would throw that exception. – Ian Gilroy Jun 07 '12 at 08:44

1 Answers1

1

You are using applicationSettings not appSettings.
The two are different sections of you config file.

To use an entry in the applicationSettings you use this syntax:

string result = Client.Properties.Settings.Default.client_postCodeRef_Service;

also note that you can't easily change the value of an applicationSetting entry from inside your program.
A detailed discussion on the pros and cons of applicationSettings and AppSettings can be found here

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • thanks steve. This is first time i have been using the config file, the discussion you refered to cleared that up. – Jed I Jun 07 '12 at 09:05