从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
部分为空。我很确定这是错的,但也许我错过了什么?
答案 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
文件。