Solved

Writing to App.Config File in C#

Posted on 2016-07-21
17
73 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
 

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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

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 to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now