How to read Windows Service configuration while starting the Windows Service?
13,366
Solution 1
The exception suggests that there is something wrong with your configuration file. Check it carefully. There should be more information in the exception or its inner exception which will give you a more precise indication of what's wrong.
Solution 2
You could try using Settings
instead, and access via Properties.Settings
.
Check out this link for more information on doing so.
Author by
Learner
Updated on June 04, 2022Comments
-
Learner almost 2 years
I am not able to read the
appSettings
from the config file (MyService.exe.config
) of my Windows Service. Please note that service is installed successfully.[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] public class MyService : ServiceBase { public MyService() { InitializeComponent(); ServiceName = ConfigurationManager.AppSettings.Get("ServiceName"); } private void InitializeComponent() { try { AutoLog = true; CanStop = true; } catch (Exception e) { // Log error } } static void Main() { MyService myService = new MyService (); Run(myService); } protected override void OnStart(string[] args) { // Code to do necessary things on start } }
The exception in the event viewer is
System.Configuration.ConfigurationErrorsException
Which is the correct location to read the configuration of the Windows Service?
ConfigurationManager.AppSettings
returnsnull
always. -
Chris Dickson about 13 years-1 Reference to
svchost.exe
isn't correct. When you useServiceBase
you usually host your service in your own process, as the OP has clearly done (MyService.exe). -
Learner about 13 yearsI have some custom
configSections
. When myappSettings
section is at the end of the config file, everything works fine! But when it's at the beginning, before `configSections', it throws the error. I am still investigating. But do you know if any particular order is supposed to be followed, by any chance ? -
Chris Dickson about 13 years@CSharpLearner:
configSections
has to come first. The config file schema is documented somewhere on MSDN, though not all that straightforward to find. -
Learner about 13 yearsAccepting your response as the answer. You correctly identified that the problem would be with the config file itself. The code as it works fine once config file is fixed.
-
Chris Dickson about 13 years@CSharpLearner: You're keeping me in suspense for my little green tick :-) ... glad I helped you solved your problem.