C# 数据库连接字符串的windows服务的System.NullReferenceException
我正在编写windows服务,使用try捕获异常:C# 数据库连接字符串的windows服务的System.NullReferenceException,c#,configurationmanager,C#,Configurationmanager,我正在编写windows服务,使用try捕获异常: try { connStr = System.Configuration.ConfigurationManager.AppSettings["connStr"].ToString(); } catch (Exception ex) { logger.Error("get the connection string failed,detail:" + ex.ToString()); } 输出为: 获取连接字符串失败,详细信息:
try
{
connStr = System.Configuration.ConfigurationManager.AppSettings["connStr"].ToString();
}
catch (Exception ex)
{
logger.Error("get the connection string failed,detail:" + ex.ToString());
}
输出为:
获取连接字符串失败,详细信息:System.NullReferenceException:未使用对象引用设置实例
它无法正确获取连接字符串
这是我的配置文件(app.config):
哪里错了?为什么无法获取连接字符串
我一直在谷歌搜索,找不到哪里错了
有什么原因会导致这个问题
堆栈轨迹:
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
2013-12-13 21:37:19895[17]错误应用信息日志[(空)]
-获取连接字符串失败,详细信息:
System.NullReferenceException:未设置具有对象引用的实例。
在Jsptpd.JobScheduler.jsptpdJobScheduler.OnStart(字符串[]args)位置
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\jsptpdjobschedule.cs:第41行
您在ConfigurationManager的错误部分查找
尝试将ConnectionString放入web.config的ConnectionString区域并调用
connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"];
如果仍然存在问题,请在该行上放置一个断点,查看正在加载的连接字符串。尝试以下方法:
connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
这是因为您的程序位置没有programName.exe.config文件,ConfigurationManager无法访问内容,因此请确保该文件存在 或者,您可以链接到此处以了解有关ConfigurationManager的更多信息:
您的意思是什么?异常的堆栈跟踪,它显示异常发生的位置。如果有.NET framework符号,您将获得更有用的堆栈跟踪。您可能应该改用ConfigurationManager的ConnectionString属性。当然,要正确使用配置文件。进入可执行文件路径,检查是否有包含正确内容的ProgrammName.exe.config,以确保配置到位且有效。如果没有此文件,我该怎么办?我本来以为是这样,但注意到他实际上在配置文件的AppSettings部分中存储了字符串
connStr = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;