System.NullReferenceException with windows service of DB connection string

核能气质少年 提交于 2019-12-11 02:38:48

问题


I am writting a windows service, and I catch an exception using try:

try
{
    connStr = System.Configuration.ConfigurationManager.AppSettings["connStr"].ToString();
}
catch (Exception ex)
{

    logger.Error("get the connection string failed,detail:" + ex.ToString());
}

The output is:

get the connection string failed,detail:System.NullReferenceException: not set an instance with a object reference.

It can't get the connection string correctly.

And this is my configuration file(app.config) :

<configuration>
    <appSettings>
        <add key="log4net.Internal.Debug" value="true"/>
        <add key="connStr" value="Data Source=Dolphin-PC;Initial Catalog=jsptpd_SYS;Persist Security Info=True;User ID=sa;Password=ccir"/>
    </appSettings>
</configuration>

Where is wrong? Why can't get the connection string?

I've been searching from google and can't find where is wrong?

Some reason can cause the problem?

The stack track:

 2013-12-13 21:37:19,895 [17] ERROR ApplicationInfoLog [(null)] <(null)>
   - get connection string failed,detail:
     System.NullReferenceException:  not set an instance with a object reference.
     on Jsptpd.JobScheduler.jsptpdJobScheduler.OnStart(String[] args) location     

 D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\jsptpdJobShedule.cs:line 41

回答1:


Try this one:

connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;



回答2:


It is because your program location don't have a programName.exe.config file,the ConfigurationManager can't access the content,so make sure the file exist.

Or you can link there to know more about ConfigurationManager :

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx




回答3:


You're looking in the wrong part of the ConfigurationManager.

Try putting the ConnectionString in the ConnectionStrings area of the web.config and calling

connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"];

If you're still having issues put a breakpoint on the line and see which ConnectionStrings are being loaded.



来源:https://stackoverflow.com/questions/20568001/system-nullreferenceexception-with-windows-service-of-db-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!