Get appSettings configSource from code

Is there a way to get configSource from code? I founded How to programmatically retrieve a configuration location from a configuration file , but all the answers are incorrect.

I have the following configuration:

<configuration> <appSettings configSource="appsettings.config"/> </configuration> 

When I tried to call the following code:

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var file = config.AppSettings.File; 

file always empty. The same goes for ConfigurationManager.AppSettings["configSource"] . I think something has changed in .NET 4 because the answers are old. I also tried config.AppSettings.SectionInformation.ConfigSource , but it is also empty.

I need this way to monitor appSettings . You can read more: How do I know if changes in an application have changed in C #?

+4
source share
1 answer

I have some problems with this, but I finally found the answer.

When the configuration file looks like this:

 <configuration> <appSettings file="appsettings.config"/> </configuration> 

The above code works correctly:

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var file = config.AppSettings.File; 

But when the configuration file (it works the same as above, but the syntax is different):

 <configuration> <appSettings configSource="appsettings.config"/> <!-- configSource instead of file --> </configuration> 

I should use the following:

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var file = config.AppSettings.SectionInformation.ConfigSource; 

Therefore, I have to check if config.AppSettings.SectionInformation.ConfigSource and config.AppSettings.File are not an empty string and check that it is correct.

+3
source

Source: https://habr.com/ru/post/1496862/


All Articles