Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 240
  • Last Modified:

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

0
teknovation
Asked:
teknovation
  • 9
  • 8
1 Solution
 
YZlatCommented:
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
 
teknovationAuthor Commented:
Can't tell , since it fails randomly, whenever I debug it never fails.
0
 
YZlatCommented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
teknovationAuthor Commented:
Thanks!
0
 
teknovationAuthor Commented:
Actually this didnt work! I got the error again this morning
0
 
YZlatCommented:
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
 
teknovationAuthor Commented:
can you assist with sample code?
0
 
YZlatCommented:
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
 
teknovationAuthor Commented:
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
 
YZlatCommented:
try adding this line

ConfigurationManager.RefreshSection("appSettings");

Open in new window


after

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

Open in new window

0
 
teknovationAuthor Commented:
Didn't work, rebooted machine and still fails when running for the first time
0
 
YZlatCommented:
Do you know exact line it fails on? Anything found in the log file?
0
 
teknovationAuthor Commented:
The log file didn't create could you give me the exact syntax?
0
 
YZlatCommented:
could you post your updated code?
0
 
teknovationAuthor Commented:
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
 
YZlatCommented:
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
 
teknovationAuthor Commented:
No file is created in the c drive
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 9
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now