[英]ConfigurationManager - get section inside of section group
I'm trying to do something very simple: Read the contents of a section that is part of a section group in my App.config file. 我正在尝试做一些非常简单的事情:读取属于我的App.config文件中的节组的一部分的内容。
This should be easy - right? 这应该很容易 - 对吗?
Turns out I've been trying to do this for an hour, tons of googling and debugging, and I just can't do it. 事实证明,我一直试图这样做一个小时,大量的谷歌搜索和调试,我只是不能这样做。 When I use
ConfigurationManager.GetSection
, it returns null
- this only works when the desired section is not part of a section group. 当我使用
ConfigurationManager.GetSection
,它返回null
- 这仅在所需部分不是部分组的一部分时才有效。
All I've found so far is this page by Microsoft that suggests parsing the XML myself. 到目前为止,我发现的只有微软的这个页面,建议自己解析XML。 Seriously!?!?
说真的!?!?
I hope someone can help me, because right now this just makes me wanna hack it together with YAML in 5 minutes and never use .NET in the future. 我希望有人可以帮助我,因为现在这只是让我想在5分钟内与YAML一起破解它,并且从未使用过.NET。
You should be able access them as key/value pairs: 您应该能够以键/值对的形式访问它们:
NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("SectionName");
string userName = section["userName"];
Try casting and see if you get the same result. 尝试投射,看看你是否得到相同的结果。 If not the Linq to XML answer is always a good fallback.
如果不是Linq to XML的答案总是一个很好的后备。
var section = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).Root.Element("SectionName");
var userName= (string)section.Element("SomeElement").Elements("add")
.Where(x => (string)x.Attribute("key") == "userName")
.Single().Attribute("value");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.