?
Solved

Writing to App.Config File in C#

Posted on 2016-07-21
17
Medium Priority
?
219 Views
Last Modified: 2016-07-28
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

0
Comment
Question by:teknovation
  • 9
  • 8
17 Comments
 
LVL 35

Expert Comment

by:YZlat
ID: 41723581
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
0
 

Author Comment

by:teknovation
ID: 41723586
Can't tell , since it fails randomly, whenever I debug it never fails.
0
 
LVL 35

Accepted Solution

by:
YZlat earned 2000 total points
ID: 41723589
try something like

config.AppSettings.Settings.Add("OrderNumber", value);

Open in new window


I think the issue is that when you run it the first time, the entry for orderNumber is not there yet, so config.AppSettings.Settings["OrderNumber"] is null, hence the error.

Actually replace

config.AppSettings.Settings["OrderNumber"].Value = value;

Open in new window

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

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Closing Comment

by:teknovation
ID: 41723843
Thanks!
0
 

Author Comment

by:teknovation
ID: 41724716
Actually this didnt work! I got the error again this morning
0
 
LVL 35

Expert Comment

by:YZlat
ID: 41727784
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
0
 

Author Comment

by:teknovation
ID: 41728022
can you assist with sample code?
0
 
LVL 35

Expert Comment

by:YZlat
ID: 41728321
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
0
 

Author Comment

by:teknovation
ID: 41729470
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?
0
 
LVL 35

Expert Comment

by:YZlat
ID: 41729478
try adding this line

ConfigurationManager.RefreshSection("appSettings");

Open in new window


after

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

Open in new window

0
 

Author Comment

by:teknovation
ID: 41729491
Didn't work, rebooted machine and still fails when running for the first time
0
 
LVL 35

Expert Comment

by:YZlat
ID: 41729493
Do you know exact line it fails on? Anything found in the log file?
0
 

Author Comment

by:teknovation
ID: 41729534
The log file didn't create could you give me the exact syntax?
0
 
LVL 35

Expert Comment

by:YZlat
ID: 41729583
could you post your updated code?
0
 

Author Comment

by:teknovation
ID: 41733045
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

0
 
LVL 35

Expert Comment

by:YZlat
ID: 41733065
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

0
 

Author Comment

by:teknovation
ID: 41733547
No file is created in the c drive
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
There may be issues when you are trying to access Outlook or send & receive emails or due to Outlook crash which leads to corrupt or damaged PST file. To eliminate the corruption from your PST file, you need to repair the corrupt Outlook PST file. U…
Suggested Courses
Course of the Month9 days, 15 hours left to enroll

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question