简体   繁体   English

如何从以特定名称开头的appsettings键中获取所有值,并将其传递给任何数组?

[英]How to get all the values from appsettings key which starts with specific name and pass this to any array?

In my web.config file I have 在我的web.config文件中

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

I want to get the value of key that starts with Service1URL and pass the value to string[] repositoryUrls = { ... } in my C# class. 我想获取以Service1URL开头的key的值,并将该值传递给C#类中的string[] repositoryUrls = { ... } How can I achieve this? 我该如何实现?

I tried something like this but couldn't grab the values: 我尝试了类似的方法,但无法获取值:

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

    string[] repositoryUrls = { value };
}

Either I am doing it the wrong way or missing something here. 我可能做错了方法,或者在这里遗漏了一些东西。 Any help would really be appreciated. 任何帮助将不胜感激。

I'd use a little LINQ: 我会用一些LINQ:

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

You are overwriting the array for every iteration 您正在为每次迭代覆盖数组

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();

I defined a class to hold the variables I am interested in and iterate through the properties and look for something in the app.config to match. 我定义了一个类来保存我感兴趣的变量,并遍历属性并在app.config中查找要匹配的内容。

Then I can consume the instance as I wish. 然后,我可以根据需要使用该实例。 Thoughts? 有什么想法吗?

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;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM