C# 交互本身作为具有单独应用程序配置文件的单独应用程序运行。如果你在 C# 交互中运行它:
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
你会看到类似的东西:
"<path to VS>\\CommonExtensions\\Microsoft\\ManagedLanguages\\VBCSharp\\InteractiveComponents\\InteractiveHost.exe.Config"
这就是正在使用的配置文件。当然它不包含您的变量,因此尝试执行 ConfigurationManager.AppSettings["foo"].ToString() 的代码会失败。
在运行时设置配置文件的常用方法是:
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", fullPathToYourConfig);
但是,这应该在对配置文件进行任何访问之前完成。首次访问时 - 正在缓存文件,随后对路径的更改将无效。不幸的是,在允许您访问执行命令之前,C# 交互式已经可以使用该文件。
有各种通过反射来重置缓存的技巧。例如(从here逐字复制):
public static void ChangeConfigTo(string path)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
typeof(ConfigurationManager)
.GetField("s_initState", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, 0);
typeof(ConfigurationManager)
.GetField("s_configSystem", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
typeof(ConfigurationManager)
.Assembly.GetTypes()
.Where(x => x.FullName ==
"System.Configuration.ClientConfigPaths")
.First()
.GetField("s_current", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
}
考虑到所有这些,如果您将该函数放在 github 上示例中的 Program 类中,并在 C# 交互中执行此操作:
Program.ChangeConfigTo(Path.GetFullPath("app.config"));
您的代码将按预期工作。您可以将此 hack 放在单独的脚本 (.csx) 文件中,并在必要时使用“#load”加载它。