I have a project with multiple configuration files, I need to be able to read a specific configuration file (MyTest.exe.config).
The file looks like this:
<appSettings>
<add key="Setting1" value="1.1.1.1"/>
<add key="Setting2" value="34567"/>
<add key="Setting3" value="blue"/>
<add key="Setting4" value="plastic"/>
</appSettings>
Code to read it looks like this:
try
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "MyTest.exe.config";
Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var appSettings = configFile.AppSettings.Settings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key].ToString());
}
}
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
But I only get the keys and no values
Output:
Key: Setting1 Value: System.Configuration.KeyValueConfigurationElement
Key: Setting2 Value: System.Configuration.KeyValueConfigurationElement
Key: Setting3 Value: System.Configuration.KeyValueConfigurationElement
Key: Setting4 Value: System.Configuration.KeyValueConfigurationElement
I also tried to get one value at a time:
try
{
String key = "Setting1";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "MyTest.exe.config";
Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var appSettings = configFile.AppSettings.Settings;
string result = appSettings[key].ToString();
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
But same thing - the output is:
System.Configuration.KeyValueConfigurationElement
Any help is greatly appreciated
maybe you must use property value:
and later, to obtain value you must use:
Try and good luck