ConfigurationSettings.AppSettings为空,抛出null异常

时间:2009-10-21 16:48:25

标签: fitnesse appsettings configurationmanager

我有一个这样的课程:

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

当我尝试使用它时:

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

我收到错误:“System.Reflection.TargetInvocationException:调用目标抛出了异常.---> System.NullReferenceException:对象引用未设置为对象的实例。” AppSettings的AllKeys属性是一个零长度的数组,我希望长度为1。

项目中的app.config文件如下所示:

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

我知道ConfigurationSettings.AppSettings应该是过时的,我应该使用ConfigurationManager.AppSettings,但我甚至无法编译。我在项目中有一个参考System.configuration(我机器上的c:\ WINDOWS \ Microsoft.NET \ Framework \ v2.0.50727 \ System.configuration.dll)并在我的代码顶部使用语句。

我正在使用Fitnesse来测试代码,那是我收到错误的时候。我的理解是,我还应该将app.config文件的副本放在我已经完成的测试夹具项目的Bin&gt; Debug文件夹中。所以,我不知道为什么我仍然会收到这个错误。

请帮助。

3 个答案:

答案 0 :(得分:6)

另外:尝试使用 ConfigurationManager 类而不是“ConfigurationSettings”:

首先使用NOT NULL检查:

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

这是在类库程序集中吗?那些从不使用自己的app.config - 而是使用主机应用程序的app.config(使用类库的应用程序)。

马克

答案 1 :(得分:2)

当您使用FitNesse进行测试时,实际运行的可执行文件是“FitServer.exe”,因此AppSettings正在FitServer.exe所在的目录中查找“FitServer.exe.config”。因此,快速而肮脏的解决方案是将app.config复制到那里并重命名。

更好的解决方案是指定应用配置,如下所述:  http://www.syterra.com/FitnesseDotNet/ApplicationConfigurationFile.html

或者如果您正在使用fitSharp(这是FitNesse.NET的增强功能):  http://www.syterra.com/Fit/AppConfigFiles.html

答案 2 :(得分:0)

请勿将其放入appsettings中。使用&lt; connectionStrings&gt;

示例:

&LT;的appSettings /&GT;

&LT;&的ConnectionStrings GT;     &lt; add name =“NORTHWNDConnectionString”connectionString =“Data Source =。\ SQLEXPRESS; AttachDbFilename = | DataDirectory | \ NORTHWND.MDF; Integrated Security = True; User Instance = True”providerName =“System.Data.SqlClient”/&gt;

&LT; /&的ConnectionStrings GT;

string cnstr = ConfigurationManager.ConnectionStrings [“NORTHWNDConnectionString”]。ToString();

相关问题