Configuration.SaveAs写入空配置

时间:2016-09-19 22:24:52

标签: c# .net

从Configuration类中获取一些奇怪的行为。这段代码

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

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>

将以下内容写入“ReadConfig.config”

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

并打印此

  

仍然破碎。

在调试视图中查看它,AppDomain.CurrentDomain.SetupInformation.ConfigurationFile具有正确的文件,但OpenExeConfiguration似乎创建了一个空白配置。 appSettings部分为空。我很确定这是错的,但也许我错过了什么?

1 个答案:

答案 0 :(得分:1)

试试这个:

        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");

OpenExeConfiguration需要DLL / EXE的路径,.config文件。