C# 从appSettings中提取电子邮件地址

C# 从appSettings中提取电子邮件地址,c#,web-config,app-config,C#,Web Config,App Config,我正在尝试从app.config文件的appSettings部分提取电子邮件地址。每次运行测试时,reportRecipients都为Null。有人能看出我做错了什么吗 <appSettings> <add key="Overdue_Report_Recipients" value="myemail@email.com"/> </appSettings> string reportRecipients = ConfigurationManag

我正在尝试从app.config文件的appSettings部分提取电子邮件地址。每次运行测试时,reportRecipients都为Null。有人能看出我做错了什么吗

  <appSettings>
    <add key="Overdue_Report_Recipients" value="myemail@email.com"/>
  </appSettings>

string reportRecipients = ConfigurationManager.AppSettings["Overdue_Report_Recipients"];

string reportRecipients=ConfigurationManager.AppSettings[“过期的报告收件人”];
谢谢

编辑: 这适用于非web应用程序的项目。这是一个解决方案的一部分,其中大多数项目是web应用程序,但这个特定项目是一项服务。很抱歉与asp.net标记混淆,我已将其删除

我在应用程序设置中存储了另一个值,我可以从中获取数据

<add key="Sweeper_Notify_When_None_Overdue" value="false"/> 

bool sendWhenNoneOverdue = 
                Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["Sweeper_Notify_When_None_Overdue"]);

bool send whennone过期=
Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings[“当没有过期时清扫器通知]);
回答: 我在一个单独的项目中运行我的测试,测试读取的是测试项目中的配置文件,而不是我正在测试的项目中的app.config。 我不得不将设置复制到测试项目中的配置中,然后测试就开始了。

var reportRecipients = ConfigurationManager.AppSettings["Overdue_Report_Recipients"].ToString();
更新

我刚刚在自己的代码中指出,没有必要使用.ToString(),您所拥有的应该可以正常工作

只是确认一下,web.config应该类似于

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="Overdue_Report_Recipients" value="myemail@email.com"/>
  </appSettings>
</configuration>

使用ASP.NET,
部分应位于
web.config
文件中,而不是您描述的
app.config

当您从
asp.net
网站或web应用程序中调用
ConfigurationManager.AppSettings[“某些键”]
时,它将查看
web.config
文件。如果您已将密钥存储在app.config文件中,这就是它返回空值的原因

如果愿意,您也可以将应用程序设置存储在web.config的单独文件中。为此,请在web.config中输入:

<configuration>
  <appSettings file="someSettingsFile.config" />
  ...
</configuration>

...
然后在someSettingsFile.config中:

<appSettings>
    <add key="Overdue_Report_Recipients" value="myemail@email.com"/>
</appSettings>


但是,我怀疑您只是将
appSettings
的位置放错了文件中。只需将它移动到您的
web.config
,您应该会没事。

我在一个单独的项目中运行测试,测试读取的是测试项目中的配置文件,而不是我正在测试的项目中的app.config。我不得不将设置复制到测试项目中的配置中,然后测试就开始了。

你的web.config中有这个,对吗?在“configuration”->“configSections”???@Zachary下,我同意我认为Ronald可能没有元素。如果使用索引0而不是键,会得到什么?可以在web.config中指定要使用的文件,例如:它在App.config中而不是web.config OP注意到App.Settings文件的使用,但应将web.config用于ASP.NET项目。我在回答中已经注意到了这一点。是否有办法使用app.config文件执行此操作?您可以尝试引用app.config文件作为
appSettings
部分的外部引用,就像在您的web.config
中一样,但我不确定其后果。我想应该有用。ASP.NET将始终首先查看web.config,因此如果要为节使用单独的文件,则必须使用
file=“
属性。