我有一个项目与多个配置文件,我需要能够读取一个特定的配置文件(MyTest.exe.config).

文件看起来像这样:

<appSettings>
    <add key="Setting1" value="1.1.1.1"/>   
    <add key="Setting2" value="34567"/>   
    <add key="Setting3" value="blue"/>    
    <add key="Setting4" value="plastic"/>  
</appSettings>

代码读它看起来像这样:

try
{
    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    fileMap.ExeConfigFilename = "MyTest.exe.config";
    Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    var appSettings = configFile.AppSettings.Settings;

    if (appSettings.Count == 0)
    {
        Console.WriteLine("AppSettings is empty.");
    }
    else
    {
        foreach (var key in appSettings.AllKeys)
        {
            Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key].ToString());
        }
    }
}
catch (ConfigurationErrorsException)
{
    Console.WriteLine("Error reading app settings");
}

但我只得到密钥没有值

输出:

Key: Setting1 Value: System.Configuration.KeyValueConfigurationElement
Key: Setting2 Value: System.Configuration.KeyValueConfigurationElement
Key: Setting3 Value: System.Configuration.KeyValueConfigurationElement
Key: Setting4 Value: System.Configuration.KeyValueConfigurationElement

我也try 一次获得一个值:

try
{
    String key = "Setting1";

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    fileMap.ExeConfigFilename = "MyTest.exe.config";

    Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

    var appSettings = configFile.AppSettings.Settings;
   
    string result = appSettings[key].ToString();

    Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
    Console.WriteLine("Error reading app settings");
}

但同样的事情—输出是:

System.Configuration.KeyValueConfigurationElement 

任何帮助都是非常感激的.

推荐答案

也许你必须使用属性值:

foreach (var key in appSettings.AllKeys)
{
    Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key].Value);
}

以后,为了获得价值,你必须使用用途:

string result = appSettings[key].Value; 

试试吧祝你好运

Csharp相关问答推荐

[0-n]范围内有多少个Integer在其小数表示中至少包含一个9?

IComponition.获取IReadOnlyCollection的返回默认属性值

在Dapper中使用IasyncEum重写GetAsyncEum方法

如何使用C#和Graph API从Azure Directory获取用户详细信息

在C#中,DirectoryEntry返回空AuditRules集合,即使审计规则确实存在

将轮询与超时同步

MongoDB.NET-将数据绑定到模型类,但无法读取整数值

实体框架核心中的ComplexType和OwnsOne有什么不同?

EF核心区分大小写的主键

ASP.NET Core MVC将值从视图传递到控制器时出现问题

用于ASP.NET核心的最小扩展坞

为什么Swashbakle/Swagger在参数中包含变量名?

如何从SignalR获取连接客户端的域

在C#中通过Matheval使用自定义公式

SignalR跨域

在.Net 8 Visual Studio 2022中启用本机AOT发布时发布失败

用于分钟和秒验证的MudTextfield的正则表达式掩码

外部应用&&的LINQ;左外部连接&类似于PostgreSQL的查询

与Visual Studio 2022中的.NET框架相比,如何在.NET Core 6中获取错误输出的窗口句柄

如何在C#中用Serilog记录类路径、方法名和行编号