32

在我的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的值并将该值传递给string[] repositoryUrls = { ... }我的 C# 类。我怎样才能做到这一点?

我尝试了这样的事情,但无法获取值:

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

    string[] repositoryUrls = { value };
}

要么我做错了,要么在这里遗漏了一些东西。任何帮助将不胜感激。

4

3 回答 3

79

我会使用一点 LINQ:

string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys
                             .Where(key => key.StartsWith("Service1URL"))
                             .Select(key => ConfigurationManager.AppSettings[key])
                             .ToArray();
于 2013-03-11T00:56:53.437 回答
13

您正在为每次迭代覆盖数组

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();
于 2013-03-11T00:50:16.310 回答
1

我定义了一个类来保存我感兴趣的变量并遍历属性并在 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;
 }
于 2015-04-17T12:53:08.940 回答