简体   繁体   中英

Cannot find my config file

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

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;
            }
        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM