Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationSettings.AppSettings is empty, throws null exception

I have a class like this:

public class RxNormFolderMgr
{
    // properties
    public string RxNormFolder { get { return ConfigurationSettings.AppSettings["rootFolder"].ToString(); } }
}

When I try to use it like this:

public class TestRxNormFolderManager : ColumnFixture
{
    public string RxNormFolder()
    {
        RxNormFolderMgr folderMgr = new RxNormFolderMgr();
        return folderMgr.RxNormFolder;
    }
}

I get an error: "System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object." The AllKeys property for AppSettings is an array of zero length where I am expecting length of 1.

My app.config file in the project looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="rootFolder" value ="C:\RxNorm" />
        <!-- Root folder must not end with slash. -->
    </appSettings>
</configuration>

I know ConfigurationSettings.AppSettings is supposed to be obsolete and I should use ConfigurationManager.AppSettings, but I can't even get that to compile. I do have a reference in the project to System.configuration (c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll on my machine) and using statement at top of my code.

I am using Fitnesse to test the code, and that's when I get the error. It's my understanding that I should also place a copy of the app.config file in the Bin>Debug folder of the test fixtures project which I have done. So, I don't know why I'm getting this error still.

Please, help.

like image 993
Marvin Avatar asked Mar 13 '26 12:03

Marvin


1 Answers

Also: try using the ConfigurationManager class instead of "ConfigurationSettings":

Use a check for NOT NULL first:

public class RxNormFolderMgr
{
    // properties
    public string RxNormFolder 
    { 
       get
       { 
           if(ConfigurationManager.AppSettings["rootFolder"] != null)
           {
               return ConfigurationManager.AppSettings["rootFolder"].ToString(); 
           }
           return string.Empty;
       }
    }
}

Is this inside a class library assembly? Those never use their own app.config - but instead the use the host app's app.config (the app that uses the class library).

Marc

like image 120
marc_s Avatar answered Mar 15 '26 10:03

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!