簡體   English   中英

如何在啟動Windows服務時閱讀Windows服務配置?

[英]How to read Windows Service configuration while starting the Windows Service?

我無法從Windows服務的配置文件( MyService.exe.config )中讀取appSettings 請注意,服務已成功安裝。

  [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

例外情況表明您的配置文件有問題。 仔細檢查。 異常或其內部異常應該有更多信息,這將使您更准確地指出錯誤。

您可以嘗試使用Settings ,然后通過Properties.Settings訪問。

有關執行此操作的詳細信息,請查看此鏈接

Windows服務將托管在svchost.exe 所以exe名稱會有所不同,因此無法加載.NET創建的配置。 您可以

  • 嘗試使用svchost.exe.config並查看.NET是否加載了配置
  • 使用ConfigurationManager.OpenExeConfiguration打開特定的配置文件並讀取值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM