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.
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.
All I've found so far is this page by Microsoft that suggests parsing the XML myself. 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.
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.
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.