Roslyn 中的 ConfigurationManager.AppSettings 返回一个空字符串



我完全知道这个问题已经在这里被问过多次了,但我在互联网上搜索了一下,还没有找到解决方案。

我使用 scriptcs 运行以下 .csx 文件(只是为了测试并确保配置管理器正常工作(:

#load "C:TicketsLoadConfig.csx"
using System;
using System.Configuration;
Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Console.WriteLine(ConfigurationManager.AppSettings.AllKeys);

这是LoadConfig.csx,我在这里找到它 SO 帖子,很多人说他们有很好的结果。

#r "System.Configuration"
using System;
using System.IO;
using System.Linq;
var paths = new[] { Path.Combine(Environment.CurrentDirectory, "web.config"), Path.Combine(Environment.CurrentDirectory, "app.config") };
var configPath = paths.FirstOrDefault(p => File.Exists(p));
if (configPath != null)
{
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath);
    var t = typeof(System.Configuration.ConfigurationManager);
    var f = t.GetField("s_initState", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
    f.SetValue(null, 0);
    Console.Write(configPath); // Here to make sure it found the app.config file properly
}

这也是app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="testKey" value="testValue" />
    </appSettings>
</configuration>

但是,当我运行第一个代码块时,它告诉我当前配置文件是 app.config,并且 AllKeys 属性是 System.String[] 。我已经确保所有文件都在同一个文件夹中,并且app.config也写正确。我现在只是陷入困境,不确定是否有任何其他解决方案,或者我是否完全忽略了某些东西。如果有人有任何建议,他们将不胜感激,谢谢。

这是因为您直接打印ConfigurationManager.AppSettings.AllKeys,这不是字符串,因此它只打印对象类型。

您需要使用类似的东西来迭代键

var keys = ConfigurationManager.AppSettings.AllKeys;
foreach (var key in keys)
{
    Console.WriteLine(key);
}
Console.ReadLine();

ConfigurationManager.AppSettings.AllKeys.ToList().ForEach(k => Console.WriteLine(k));

输出:

测试键

相关内容

最新更新