C# 如何在启动Windows服务时读取Windows服务配置?

C# 如何在启动Windows服务时读取Windows服务配置?,c#,.net,windows-services,C#,.net,Windows Services,我无法从Windows服务的配置文件(MyService.exe.config)中读取appSettings。请注意,服务已成功安装 [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] public class MyService : ServiceBase { public MyService() {

我无法从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

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

  • 尝试放置一个
    svchost.exe.config
    ,然后查看.NET是否加载该配置
  • 使用
    ConfigurationManager.OpenExeConfiguration
    打开特定的配置文件并读取值

您可以尝试改用
设置
,并通过
属性访问。设置


查看此操作的详细信息。

此异常表明您的配置文件有问题。仔细检查。异常或其内部异常中应该有更多的信息,这将为您提供更精确的错误指示

我有一个现有的服务,这应该可以工作:ServiceName=ConfigurationManager.AppSettings[“ServiceName”];我假设您已经检查过配置文件是否安装在服务目录中?因为问题出在配置文件中,所以代码工作正常<代码>应用设置节位于错误的位置。请参阅ChrisDickson的答案。-1对
svchost.exe
的引用不正确。当您使用
ServiceBase
时,您通常会在自己的流程中托管服务,正如OP所做的那样(MyService.exe)。我有一些自定义
configSections
。当我的
appSettings
部分位于配置文件的末尾时,一切正常!但是当它在开始时,在'configSections'之前,它抛出错误。我还在调查。但是你知道有没有什么特殊的顺序是应该遵循的吗?@csharpblearner:
configSections
必须放在第一位。配置文件模式在MSDN的某个地方有文档记录,尽管不是很容易找到。接受您的响应作为答案。您正确地确定了问题出在配置文件本身。一旦配置文件被修复,代码就可以正常工作。@CSharpLearner:你让我对我的绿色小勾号保持悬念:-)。。。很高兴我帮你解决了你的问题。