ConfigurationSettings.AppSettings为空,抛出null异常
-
05-07-2019 - |
题
我有一个这样的课程:
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;
}
}
我收到错误:<!> quot; System.Reflection.TargetInvocationException:调用目标抛出了异常。 --- GT <!>; System.NullReferenceException:未将对象引用设置为对象的实例。<!> quot; 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来测试代码,那是我收到错误的时候。我的理解是,我还应该在我已经完成的测试夹具项目的Bin <!> gt; Debug文件夹中放置app.config文件的副本。所以,我不知道为什么我仍然会收到这个错误。
请帮助。
解决方案
当您使用FitNesse进行测试时,实际运行的可执行文件是<!>“FitServer.exe <!>”;所以AppSettings正在寻找一个<!>“FitServer.exe.config <!>”;在FitServer.exe生活的目录中。因此,快速而肮脏的解决方案是将app.config复制到那里并重命名。
更好的解决方案是指定应用配置,如下所述: http://www.syterra.com/FitnesseDotNet/ApplicationConfigurationFile.html
或者如果您正在使用fitSharp(这是FitNesse.NET的增强功能): http://www.syterra.com/Fit/AppConfigFiles.html
其他提示
另外:尝试使用 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(使用类库的应用程序)。
马克
请勿将其放入appsettings中。使用<!> lt; connectionStrings <!> gt;
示例:
LT <!>;的appSettings / GT <!>;
LT <!>; <!>的ConnectionStrings GT; <!> lt; add name = <!> quot; NORTHWNDConnectionString <!> quot; connectionString = <!> quot; Data Source =。\ SQLEXPRESS; AttachDbFilename = | DataDirectory | \ NORTHWND.MDF; Integrated Security = True; User Instance = True <!> quot;的providerName = QUOT <!>; System.Data.SqlClient的QUOT <!>; / GT <!>;
LT <!>; / GT的ConnectionStrings <!>;
string cnstr = ConfigurationManager.ConnectionStrings [<!> quot; NORTHWNDConnectionString <!> quot;]。ToString();