troubleshooting Question

Writing to App.Config File in C#

Avatar of teknovation
teknovation asked on
C#.NET Programming
17 Comments1 Solution545 ViewsLast Modified:

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.

Object reference not set to an instance of an object.

<?xml version="1.0"?>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
    <add key="OrderNumber"/>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri=""/>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400"/>

public class PurchaseOrder850
 static public void Main(string[] args)
		string OrderNo = 123;

public static void ModifyAppConfig(string value)

                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. 

            catch (System.IO.IOException e)
                Console.WriteLine(e.Message + " key value passed for App Config: " +  value);

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 17 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 17 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros