jzx jzx - 2 months ago 17
C# Question

Configuration.SaveAs writes empty config

Getting some odd behavior from Configuration class. This code

class Program
{
static void Main(string[] args)
{
var configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
var value = configuration.AppSettings.Settings["Supercali"];
if (value != null) Console.WriteLine("Yay, it finally worked!");
else Console.WriteLine("Still broken.");
configuration.SaveAs("ReadConfig.config");
}
}


with this config in
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>

<appSettings>
<add key="Supercali" value="Fragalistic"/>
</appSettings>
</configuration>


writes the following to "ReadConfig.config"

<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>


and prints this


Still broken.


Looking at it in debug view,
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
has the correct file, but
OpenExeConfiguration
seems to create a blank config. The
appSettings
section is empty. I'm pretty sure this is wrong, but maybe I'm missing something?

rbm rbm
Answer

Try this:

        var configFile = Assembly.GetExecutingAssembly().Location;
        var configuration = ConfigurationManager.OpenExeConfiguration(configFile);
        var value = configuration.AppSettings.Settings["Supercali"];
        if (value != null) Console.WriteLine("Yay, it finally worked!");
        else Console.WriteLine("Still broken.");
        configuration.SaveAs("ReadConfig.config");

The OpenExeConfiguration expects the path to a DLL/EXE, not to the .config file.