Windows Service Config File C#

2019-01-13 21:13发布

问题:

I've developed a windows service application using Visual Studio 2008 / C#.

I have an app.config file in the project. When installed, the app.exe.config file appears beside the executable but it appears not to be reading the values from it when I try to access them through ConfigurationManager.AppSettings.

Has it copied the config file elsewhere or is there some other problem I don't know about?

Thanks in advance,

Martin.

Edit: The config file name is infact my_exe_file_name.exe.config, it looks like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>

    <add key="RuntimeFrequency" value="3" />

  </appSettings>
</configuration>

and I am trying to read via:

ConfigurationManager.AppSettings["RuntimeFrequency"]

The debug value I continually see is '1' and not '3'. Am I doing something wrong here?

回答1:

I located the error and it was related to file permissions. After installing the service, my local user account didn't have access to modify the app.exe.config file.

The tool I was using to edit was not informing me it was being denied access to save the file - that's notepad++ if anyone is interested - so I couldn't see that it wasn't saving over the old config file.

Solved now, thanks everyone.

Martin.



回答2:

When you are in debug mode check and see what settings are in the my_exe_file_name.vshost.exe.config Also make sure you adjust this in the app.config file. Visual studio should update the final config file in your bin/debug folders.



回答3:

Maybe you are updating the wrong config file. You should double check that using

System.Configuration.ConfigurationManager.OpenExeConfiguration(PATH_TO_CONFIG);


回答4:

Generally for the Windows Services that I write, i drop the appName.exe.config file into C:\WINDOWS\system32\

Perhaps you have an older version in that directory, which is where your service is getting the value, even though you've updated the config file in your project.



回答5:

App.config file should be renamed to your_exe_file_name.exe.config and placed near the exe file.



回答6:

Is it possible that you have more than one instance of the RuntimeFrequency entry defined? The ConfigurationManager reads the file from top to bottom and processes each setting individually. Therefore, the last value of RuntimeFrequency that is defined in the file is the one it will use.

If you want to know for sure if your file is being used, I would simply remove or comment out any definition for RuntimeFrequency (copy/paste errors do happen) and wait to see an application error when ConfigurationManager attempts to reference an entry in AppSettings that does not exist.