如何从appsettings key中获得所有的值,它以特定的名称开始,并将其传递给任何数组

本文关键字:开始 任何 数组 key appsettings | 更新日期: 2023-09-27 18:03:27

在我的web.config文件中我有

<appSettings>
    <add key="Service1URL1" value="http://managementService.svc/"/>
    <add key="Service1URL2" value="http://ManagementsettingsService.svc/HostInstances"/>
    ....lots of keys like above
</appSettings>

我想获得以Service1URL开头的键的值,并将值传递给我的c#类中的string[] repositoryUrls = { ... }。我怎样才能做到这一点呢?

我试过这样做,但无法抓取值:

foreach (string key in ConfigurationManager.AppSettings)
{
    if (key.StartsWith("Service1URL"))
    {
        string value = ConfigurationManager.AppSettings[key];            
    }
    string[] repositoryUrls = { value };
}

要么我做错了,要么在这里遗漏了一些东西。

如何从appsettings key中获得所有的值,它以特定的名称开始,并将其传递给任何数组

我会用一点LINQ:

string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys
                             .Where(key => key.StartsWith("Service1URL"))
                             .Select(key => ConfigurationManager.AppSettings[key])
                             .ToArray();

每次迭代都覆盖数组

List<string> values = new List<string>();
foreach (string key in ConfigurationManager.AppSettings)
        {
            if (key.StartsWith("Service1URL"))
            {
                string value = ConfigurationManager.AppSettings[key];
                values.Add(value);
            }
        }
string[] repositoryUrls = values.ToArray();

我定义了一个类来保存我感兴趣的变量,并遍历属性并在app.config中寻找匹配的内容。

然后我就可以随心所欲地使用实例了。想法吗?

public static ConfigurationSettings SetConfigurationSettings
{
    ConfigurationSettings configurationsettings = new   ConfigurationSettings();
    {
        foreach (var prop in  configurationsettings.GetType().GetProperties())
        {
            string property = (prop.Name.ToString());
            string value = ConfigurationManager.AppSettings[property];
            PropertyInfo propertyInfo = configurationsettings.GetType().GetProperty(prop.Name);
            propertyInfo.SetValue(configurationsettings, value, null);
        }
    }
    return configurationsettings;
 }