Learner
Learner

Reputation: 4751

How to read Windows Service configuration while starting the Windows Service?

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 returns null always.

Upvotes: 4

Views: 14066

Answers (3)

Chris Dickson
Chris Dickson

Reputation: 12135

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.

Upvotes: 4

Aliostad
Aliostad

Reputation: 81660

Windows services will be hosted in svchost.exe. So the exe name will be different hence it will not be able to load the config created by .NET. You can

  • try putting a svchost.exe.config and see if .NET loads the config
  • Use ConfigurationManager.OpenExeConfiguration to open a specific config file and read values

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45083

You could try using Settings instead, and access via Properties.Settings.

Check out this link for more information on doing so.

Upvotes: 2

Related Questions