Avatar of teknovation
teknovation
 asked on

Writing to App.Config File in C#

All,

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.


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

Open in new window


Program.cs
----------
public class PurchaseOrder850
{
 static public void Main(string[] args)
 {
		string OrderNo = 123;
		MethodHelper.ModifyAppConfig(OrderNo);
 }
}

Open in new window


MethodHelper.cs
----------
 
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);
            }
             
        }
         

Open in new window

C#.NET Programming

Avatar of undefined
Last Comment
teknovation

8/22/2022 - Mon
YZlat

which line gives you the error?

I think the issue is that there is no entry for OrderNumber and it needs to be created first
teknovation

ASKER
Can't tell , since it fails randomly, whenever I debug it never fails.
ASKER CERTIFIED SOLUTION
YZlat

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
teknovation

ASKER
Thanks!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
teknovation

ASKER
Actually this didnt work! I got the error again this morning
YZlat

Can you debug it?

Also you could make it write detailed errors to the log so you could have al'the details whenever the error occurs
teknovation

ASKER
can you assist with sample code?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
YZlat

wrap your code in try...catch:
 
try {
     if(config.AppSettings.Settings["OrderNumber"]!=null)
	    config.AppSettings.Settings["OrderNumber"].Value = value;
     else
          config.AppSettings.Settings.Add("OrderNumber", value);
} catch (Exception ex) {
        string path=Path.Combine(Application.StartUp, "myLog.txt");

       if (! File.Exists(path))
                 File.Create(path);
         using (StreamWriter w = File.AppendText(path))
        {
                w.WriteLine(ex.Message + ":" + ex.StackTrace);
         }

}

Open in new window


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?
YZlat

try adding this line

ConfigurationManager.RefreshSection("appSettings");

Open in new window


after

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

Open in new window

Your help has saved me hundreds of hours of internet surfing.
fblack61
teknovation

ASKER
Didn't work, rebooted machine and still fails when running for the first time
YZlat

Do you know exact line it fails on? Anything found in the log file?
teknovation

ASKER
The log file didn't create could you give me the exact syntax?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
YZlat

could you post your updated code?
teknovation

ASKER
Since the write log didnt' work, I just reverted it back.

Here's my current code:

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
           ConfigurationManager.RefreshSection("appSettings");
            try
            {
               

            if (config.AppSettings.Settings["OrderNumber"] != null)
                config.AppSettings.Settings["OrderNumber"].Value = value;
            else
                config.AppSettings.Settings.Add("OrderNumber", value);

            config.Save();

            ConfigurationManager.RefreshSection("appSettings");
                 }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + " key value passed for App Config: " +  value); 
            }

Open in new window

YZlat

try this:

public static void ModifyAppConfig(string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConfigurationManager.RefreshSection("appSettings");
            try
            {


                if (config.AppSettings.Settings["OrderNumber"] != null)
                    config.AppSettings.Settings["OrderNumber"].Value = value;
                else
                    config.AppSettings.Settings.Add("OrderNumber", value);

                config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception e)
            {
                string filePath = @"C:\Error.txt";

                using (StreamWriter writer = new StreamWriter(filePath, true))
                {
                    writer.WriteLine("Message :" + e.Message + "<br/>" + Environment.NewLine + "StackTrace :" + e.StackTrace +
                       "" + Environment.NewLine + "Date :" + DateTime.Now.ToString() + Environment.NewLine);
                    
                }

            }

        }

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
teknovation

ASKER
No file is created in the c drive