Ron
Ron

Reputation: 2503

C# Opening a configuration file from an arbitrary location

At:

Using ConfigurationManager to load config from an arbitrary location I found what seems like a solution. A project I'm working on uses an appSettings.config file location on the network. BUT when I tried to use the referenced code:

 System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap("Z:\Settings\appSettings.config"); //Path to your config file

 System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

So far so good. The appSettings.config file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="Environment" value="Development" />
  </appSettings>
</configuration>

BUT then I get to this following line:

var settings = configuration.AppSettings.Settings;

or anything using it, like Settings.Count, I get an Invalid Cast Exception. Basically, how would I get the value for "Environment" from this?

Upvotes: 3

Views: 4982

Answers (1)

Ron
Ron

Reputation: 2503

I found this works:

System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

fileMap.ExeConfigFilename = @"Z:\appSettings.config"; //Path to your config file

System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); // OpenMappedMachineConfiguration(fileMap);
return configuration.AppSettings.Settings["Environment"].Value;

This works without error.

Upvotes: 6

Related Questions