I am trying to create a application via C# that writes a value to the AppConfig file. But I am often prompted with this error message when I run the program the first time. However, when I run it after the first run, it'll execute fine. Can someone explain what is happening? I try to set the debugger , but I assume it's probably a timing issue.
I tried this by executing the .exe file in the bin folder of the program so there's no issues writing to the config file.
Error:
Object reference not set to an instance of an object.
public static void ModifyAppConfig(string value) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["OrderNumber"].Value = value; Thread.Sleep(TimeSpan.FromSeconds(3)); // added this so there's time for the file to be updated, not sure if necessary. config.Save(); ConfigurationManager.RefreshSection("appSettings"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message + " key value passed for App Config: " + value); } }
and make sure you add "using System.IO" at the top of your code file.
The code above is not tested as I don't have access to Visual studio at the moment so you might need some tweaks
teknovation
ASKER
So i couldnt get your code to work but here's some new interesting finds.
When I open up the config file - the keys exist
<add key="OrderNumber" value="5924524" />
Then I decided to remove the key from the app config file and run the app and it still works and rewrites because it's not there as expected.
So it's mainly when the computer first reboots and runs the app for the first time and it fails when writing to the app config file. That is so strange - because it will fail with the same error whether or not the Order Number key exists!
Thoughts? Could it be related to security upon rebooting?
I think the issue is that there is no entry for OrderNumber and it needs to be created first