Cannot find my config file

2.9k views Asked by At

I need to read/write to a config file not related to any exe. I'm trying this:

        var appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "SlamDunkSuper.config" }, ConfigurationUserLevel.None);
        if(appConfiguration == null) {

           //Configuration file not found, so throw an exception
           //TODO: thow an exception here
        } else {

           //Have Configuration, so work on the contents
           var fileEnvironment = appConfiguration.GetSection("fileEnvironment");
        }

No exception is thrown, but fileEnvironment is always null. Here is the file contents:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="fileEnvironment" type="System.Configuration.NameValueSectionHandler"/>
   </configSections>

   <fileEnvironment>
      <add key="DxStudioLocation" value="123456"/>
   </fileEnvironment>
</configuration>

Someone please lead me out of the wilderness. I also don't know how to write, or change, an entry in the NameValueCollection, after I get the contents of the section. Thanks

2

There are 2 answers

0
KMoraz On BEST ANSWER

You can globalize AppSettingsSection with some minor adjustments:

<section name="fileEnvironment" type="System.Configuration.AppSettingsSection"/>

Consume with:

        var appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "SlamDunkSuper.config" }, ConfigurationUserLevel.None);

        if (!appConfiguration.HasFile) // no need to null check, ConfigurationManager.OpenMappedExeConfiguration will always return an object or throw ArgumentException
        {
            //Configuration file not found, so throw an exception
        }
        else
        {
            var section = appConfiguration.GetSection("fileEnvironment") as AppSettingsSection;
            if (section != null)
            {
                var dxStudioLocation = section.Settings["DxStudioLocation"].Value;
            }
        }
3
OopsUser On

In .net the config file is chosen by the running exe file, so if you have 5 projects (4 dll's and one exe), and each project has a different config file when you will run your app from the exe file the dll's which are loaded by him will think that the config file of the exe is theirs config file.

in other words, to read the config file of the dll project you need to open it explicitly using his path.

hope it helps