4

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#?

3
  • You can try using this and see if it returns the right configuration file back ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = configurationFilePath }, ConfigurationUserLevel.None); Commented Aug 13, 2013 at 17:20
  • The ConfigSource property didn't work? msdn.microsoft.com/en-us/library/… Commented Aug 13, 2013 at 17:21
  • @PeterRitchie I had to change something durring my tries. If you are interested how it works you could see my own answer Commented Aug 14, 2013 at 12:26

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.