Question

Is there a way to retrieve configSource from code? I founded How to programmatically retrieve the configSource Location from config file, but all answers are wrong.

I have following config:

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

When I tried to invoke following code:

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

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

I need this path to enable monitoring of appSettings. You could read more: How to discover that appsettings changed in C#?

Was it helpful?

Solution

I have some problems with this but I finally find an answer.

When config file looks like this:

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

The code above is working correctly:

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

But when config file is (it works same as above but syntax is different):

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

I have to use following:

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

So I have to check if config.AppSettings.SectionInformation.ConfigSource and config.AppSettings.File is not an empty string and monitor correct one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top