CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    May 2002
    Posts
    1,798

    Object reference not set to an instance of an object.

    One would expect that the skey variable was null when this error is encountered, but as the debug trace shows, both skey and svalue have strings associated as they should in the WriteToAppConfig method. How can I fix this so it works properly?

    Code:
    using System.Configuration;                // for App.config file use
    using System.Collections.Specialized;   // ""
    
    form1
    {
    //..
    
                // writing to an AppConfig file
                string skey = "Key3";
                string svalue = "Victoria Lynne Kirchner";
                WriteToAppConfig(skey, svalue);
    
    }
    
            // write to app.config file 
           private void WriteToAppConfig(string key, string value)
           {
                Debug.WriteLine("WriteToAppConfig(string key, string value)");
                Debug.WriteLine("key =: " + key);
                Debug.WriteLine("value =: " + value);
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                config.AppSettings.Settings[key].Value = value;  // Object reference not set to an instance of an object.
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
    
           }// WriteToAppConfig(string key, string value)
    mpliam

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Object reference not set to an instance of an object.

    Put a breakpoint on the following line of code:

    Code:
    config.AppSettings.Settings[key].Value = value;
    When the compiler hits the break point, hover over the AppSettings value. Is it null? Next, hover over the Settings value. It should not be null either and contain a list of the app settings entries. Does it contain an entry with the case sensitive key you are looking for?

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Object reference not set to an instance of an object.

    Put a breakpoint on the following line of code:

    Code:
    config.AppSettings.Settings[key].Value = value;
    When the compiler hits the break point, hover over the AppSettings value. Is it null? Next, hover over the Settings value. It should not be null either and contain a list of the app settings entries. Does it contain an entry with the case sensitive key you are looking for?

  4. #4
    Join Date
    May 2002
    Posts
    1,798

    Re: Object reference not set to an instance of an object.

    Thanks Arjay.

    [key] ="Key3"
    value = "Victoria Lynne Kirchner"
    These appear to be correct.

    There are lots of subfolders to look at. I found only these NULL under CurrentConfiguration:

    AppSettings
    config.AppSettings = {System.Configuration.AppSettingsSection}
    base {System.Configuration.ConfigurationSection}
    base {System.Configuration.ConfigurationElement} = {System.Configuration.AppSettingsSection}
    CurrentConfiguration = {System.Configuration.Configuration}
    AssemblyTransformer NULL
    TargetFramework NULL
    TypeStringTransformer NULL

    I still don't know what to make of it. Could I be missing an assembly? Usually the compiler warns of such.
    Last edited by Mike Pliam; April 19th, 2016 at 02:01 PM.
    mpliam

  5. #5
    Join Date
    May 2002
    Posts
    1,798

    Re: Object reference not set to an instance of an object.

    I found this little gem:
    // https://social.msdn.microsoft.com/Fo...=csharpgeneral

    Seems to work just fine and a bit more straightforward. This code will even add a new key that wasn't there before. What took awhile to catch on to was the fact that the AppConfig variable in VS IDE doesn't change when the code is run. But the changes can be seen in the bin MyParmStorage.exe.Config file. This certainly adds to the confusion of C# newbies like me.
    Code:
          private void ModifyAppConfig()
           {
                // To modify the Application.exe.config you need to use ConfigurationManager class.
              
                // Open App.Config of executable
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                // Add an Application Setting.
                config.AppSettings.Settings.Remove("LastDateChecked");
                config.AppSettings.Settings.Add("LastDateChecked", DateTime.Now.ToLongDateString());
                config.AppSettings.Settings.Remove("LastTimeChecked");
                config.AppSettings.Settings.Add("LastTimeChecked", DateTime.Now.ToLongTimeString());
                // Save the configuration file.
                config.Save(ConfigurationSaveMode.Modified);
                // Force a reload of a changed section.
                ConfigurationManager.RefreshSection("appSettings");
    
           }// ModifyAppConfig()
    I should add that the original AppConfig file was:
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="Key0" value="0" />
        <add key="Key1" value="1" />
        <add key="Key2" value="2" />
      </appSettings> 
    </configuration>
    and the resultant (bin/Release) MyParmStorage.exe.Config file.
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="Key0" value="0" />
        <add key="Key1" value="1" />
        <add key="Key2" value="2" />
        <add key="LastDateChecked" value="Tuesday, April 19, 2016" />
        <add key="LastTimeChecked" value="12:40:37 PM" />
      </appSettings> 
    </configuration>
    At least now I have something to work with but am still curious as to why the earlier code failed.
    Last edited by Mike Pliam; April 19th, 2016 at 02:49 PM.
    mpliam

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Object reference not set to an instance of an object.

    Not sure how you debugged or what you have in the app.config file.

    Given an app.config file of:
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        </startup>
    <appSettings>
      <add key="test" value="testvalue"/>
    </appSettings>
    </configuration>

    The following code works:
    Code:
    using System.Configuration;
    using System.Diagnostics;
    
    namespace CG.AppConfigWrite.Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                // NOTE: the app.config contains an appsettings section with a single entry
                //<appSettings>
                //  <add key="test" value="testvalue"/>
                //</appSettings>
    
                 WriteToAppConfig("test", "newvalue"); // Should update the value for the existing key
    
                 WriteToAppConfig("test1", "value1");  // Should insert a new entry
            }
    
            private static void WriteToAppConfig(string key, string value)
            {
                Debug.WriteLine("WriteToAppConfig(string key, string value)");
                Debug.WriteLine("key =: " + key);
                Debug.WriteLine("value =: " + value);
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
                // Check if the key exists
                if (config.AppSettings.Settings.AllKeys.Contains(key))
                {
                    // Exists, set the new value
                    config.AppSettings.Settings[key].Value = value;
                }
                else
                {
                    // Doesn't exist, so add a new entry
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement(key, value));
                }
    
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
        }
    }
    Keep in mind that when you debug under Visual Studio, the changed config file will be under bin/debug and called xxx.vshost.exe.Config where xxx is the name of your program.

    Open this file from the bin/debug directory while you are debugging and you will get prompted to reload the file in the IDE when your program changes the file. In the same code I provide, you should get prompted twice.

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Object reference not set to an instance of an object.

    Given all that, I should mention that it generally isn't thought to be a best practice to write to the app.config file.

    Usually app.config files are read-only, non-user specific data. If you need to save user-specific data, there are other options.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured