0

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

我使用 scriptcs 运行以下 .csx 文件(只是为了测试并确保 ConfigurationManager 工作):

#load "C:\Tickets\LoadConfig.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 也正确写入。我现在只是卡住了,不确定是否还有其他解决方案,或者我是否完全忽略了某些东西。如果有人有任何建议,他们将不胜感激,谢谢。

4

1 回答 1

0

这是因为您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));

输出:

测试密钥

于 2017-11-16T02:30:19.573 回答