15492

System.NullReferenceException with windows service of DB connection string

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

Answer1:

Try this one:

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

Answer2:

It is because your program location don't have a <strong>programName.exe.config</strong> 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

Answer3:

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.

Recommend

  • How to bind a single object instance in WPF?
  • Castle Windsor dependency injection: Use the caller type as a parameter
  • cf.net exception and other logging
  • Using DI in ConfigureService-Methods (especially IApplicationLifetime) in .NET Core
  • Get the SQL query issued by a LINQ command in Linq to SQL
  • .NET project with project.json cannot be built
  • PDF using WCF Restful Services
  • aapt.exe'' finished with non-zero exit value 1
  • MYSQ & MVC3 SQL connection error \\ ProviderManifestToken but I am using MySQL
  • Android app gives error “BatteryStatsImpl: reading network stats”
  • How to run “Deployd” on port 80 instead of port 5000 in webserver.
  • Can I check if a recipient has an automatic reply before I send an email?
  • SignalR .NET Client Invoke throws an exception
  • Why value captured by reference in lambda is broken? [duplicate]
  • Getting last autonumber in access
  • req.body is undefined - nodejs
  • How to get a value (ex: baseURL) in every Karate feature?
  • Symfony2: How to get request parameter
  • Akka Routing: Reply's send to router ends up as dead letters
  • Invalid access key error using credentials redeemed from an amazon open id token
  • Circular dependency while pushing http interceptor
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Is there a mandatory requirement to switch app.yaml?
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • JTable with a ScrollPane misbehaving
  • Angular 2 constructor injection vs direct access
  • -fvisibility=hidden not passed by compiler for Debug builds
  • Why joiner is not used after Sequence generator or Update statergy
  • coudnt use logback because of log4j
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • Recursive/Hierarchical Query Using Postgres
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS