如何在启动Windows服务时阅读Windows服务配置?

时间:2011-04-08 10:55:05

标签: c# .net windows-services

我无法从Windows服务的配置文件(appSettings)中读取MyService.exe.config。请注意,服务已成功安装。

  [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
            }
    }

事件查看器中的例外是System.Configuration.ConfigurationErrorsException

阅读Windows服务配置的正确位置是什么? ConfigurationManager.AppSettings始终返回null

3 个答案:

答案 0 :(得分:4)

该异常表明您的配置文件有问题。仔细检查。异常或其内部异常应该有更多信息,这将使您更准确地指出错误。

答案 1 :(得分:2)

您可以尝试使用Settings,然后通过Properties.Settings访问。

查看this link了解有关这样做的更多信息。

答案 2 :(得分:0)

Windows服务将托管在svchost.exe中。所以exe名称会有所不同,因此无法加载.NET创建的配置。你可以

  • 尝试添加svchost.exe.config并查看.NET是否加载配置
  • 使用ConfigurationManager.OpenExeConfiguration打开特定配置文件并读取值