C# 如何从以特定名称开头的 appsettings 键中获取所有值并将其传递给任何数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15329601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all the values from appsettings key which starts with specific name and pass this to any array?
提问by
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. How can I achieve this?
我想获取以开头的键Service1URL
的值并将该值传递给string[] repositoryUrls = { ... }
我的 C# 类。我怎样才能做到这一点?
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.
要么我做错了,要么在这里遗漏了一些东西。任何帮助将不胜感激。
采纳答案by Ann L.
I'd use a little LINQ:
我会使用一点 LINQ:
string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys
.Where(key => key.StartsWith("Service1URL"))
.Select(key => ConfigurationManager.AppSettings[key])
.ToArray();
回答by TGH
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();
回答by Pat
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;
}