1

I am facing an issue with getting a value from Web.config.

Here is my web.config code which contains Key

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="Email" value="myname@mydomain.com" />

i want email key value, i am writing,

  string From = ConfigurationManager.AppSettings["Email"].ToString();

but its giving me error "Object reference is not set to an instance of an object"

My other web.config declarations are:

<system.net>
    <mailSettings>
        <smtp>
            <network host="smtp.gmail.com" port="***" enableSsl="true" defaultCredentials="false" userName="myname@mydomain.com" password="mypassword" />
        </smtp>
    </mailSettings>
</system.net>

Any help appreciated! Thanks!

tereško
  • 58,060
  • 25
  • 98
  • 150
Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
  • 3
    see http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net for help on `NullReferenceException`s – pascalhein Apr 04 '13 at 11:38
  • 2
    Well is it actually looking to the config file you posted (i guess not) **Or** is it throwing error only for `Email` ? – V4Vendetta Apr 04 '13 at 11:39
  • 1
    Looks strange. Are you sure that this row is causing the exception? Or perhaps this code is called from different project than the one where web.config resides? Did you try looking at ConfigurationManager.AppSettings["Email"] value in debug? – Alexander Tsvetkov Apr 04 '13 at 11:40
  • I agree make sure that your code is pointing to correct place . Code looks fine . In debug mode check for AppSettings values – Devesh Apr 04 '13 at 11:41
  • @AlexanderTsvetkov Yes i have looked at its values but it is only showing 2 Keys [0] ClientValidationEnabled [1] UnobtrusiveJavaScriptEnabled 3rd Email key is not even in the debugging. – Dhaval Marthak Apr 04 '13 at 11:42
  • 5
    If you are working with MVC, then you will observer that there will be two web.config files, one in View directory and the second one in you project root dircetory. Make sure you have these values in the one that is in root directory of you project. – umair.ali Apr 04 '13 at 11:53
  • @umair.ali Got your point Thanks i resolved it :) – Dhaval Marthak Apr 04 '13 at 11:57
  • 1
    Another note, you do not have to call `.ToString()` on `AppSettings["key"]`. It is already a `string`. – danludwig Apr 04 '13 at 14:15

1 Answers1

1

Make sure that your start up project is set correctly. If you're running this from a separate project (i.e. in a test), it won't be looking at that Web.config but its own Web/App.config file.

Rich
  • 11
  • 1