Solved

Writing to App.Config File in C#

Posted on 2016-07-21
17
112 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 500 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
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

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

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

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.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

685 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