I'm trying to pull an email address from the appSettings section of the app.config file. Every time I run a test, reportRecipients is Null. Can anyone see what I'm doing wrong?
<appSettings>
<add key="Overdue_Report_Recipients" value="myemail@email.com"/>
</appSettings>
string reportRecipients = ConfigurationManager.AppSettings["Overdue_Report_Recipients"];
Thanks
Edit: this is for a project that is not a web app. It's part of a Solution where most of the projects are web apps but this particular one is a service. sorry for the confusion with asp.net tag i have removed it.
I have another value stored in app Settings and I'm able to get the data from it
<add key="Sweeper_Notify_When_None_Overdue" value="false"/>
bool sendWhenNoneOverdue =
Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["Sweeper_Notify_When_None_Overdue"]);
ANSWER: I was running my test in a separate project and the test was reading from the config file in the test project and not the app.config in the project I was testing. I had to copy the 开发者_开发百科settings to the config in the test project and then the test worked.
Using ASP.NET, the <appSettings>
section should be within the web.config
file, not app.config
as you describe.
When you call ConfigurationManager.AppSettings["some key"]
from within your asp.net
website or web application it is going to look in the web.config
file. If you've stored your key in the app.config file that is why it comes back null.
You can alternatively store your app settings in a separate file from web.config if you prefer. To do so, in your web.config put:
<configuration>
<appSettings file="someSettingsFile.config" />
...
</configuration>
Then in someSettingsFile.config:
<appSettings>
<add key="Overdue_Report_Recipients" value="myemail@email.com"/>
</appSettings>
I suspect however you just misplaced the location of appSettings
in the wrong file. Just move it to your web.config
and you should be fine.
var reportRecipients = ConfigurationManager.AppSettings["Overdue_Report_Recipients"].ToString();
Update.
I just noted in my own code that there is no need for the .ToString() and what you have there should work fine.
Just to confirm, web.config should be similiar to;
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Overdue_Report_Recipients" value="myemail@email.com"/>
</appSettings>
</configuration>
I was running my test in a separate project and the test was reading from the config file in the test project and not the app.config in the project I was testing. I had to copy the settings to the config in the test project and then the test worked.
精彩评论