How to read web.config section as XML in C#?

萝らか妹 提交于 2019-12-14 04:18:00

问题


This is copied example from:

How to read custom config section in app.config in c#

I want to read following custom section from app.config:

<StartupFolders>    
   <Folders name="a">
      <add folderType="Inst" path="c:\foo" />
      <add folderType="Prof" path="C:\foo1" />      
   </Folders>
   <Folders name="b">
      <add folderType="Inst" path="c:\foo" />
      <add folderType="Prof" path="C:\foo1" />      
   </Folders> 
</StartupFolders>

And this is my case too. However, I don't want to create custom class for handling values, defining this class in web.config, and then finally using it. It is heavy-weight for my needs.

Instead I would like to do something very simple -- retrieve a section as XML. Then I could use regular Linq.Xml to parse it. This way, I don't need to create new classes per each section, I don't need to declare them. For my purpose it is sufficient on one hand, and minimal at the other (I do it once, key-value mapper for nested sections). I.e. perfect.

The only missing piece is (my question) -- how to get a web.config section as XML? Note about the section:

  • it cannot be encoded, because it has to be edited by hand
  • it cannot be serialized for the same reason

So I am not looking for a workaround how to squeeze entire section as value in appSettings, but I am really looking for a method to get proper section as XML.

I would like to get it from ConfigManager (!), because this way I don't have to deal with resolving which web.config should I read, etc. I.e. less chance to make mistake than mimicing web.config precedence manually.


Forgive me for reminding this, but please avoid "answers", you shouldn't do this, use custom class per each section, etc. I already considered this, and opted against it.


回答1:


I think you either have to do it manually and load the Web config into memory:

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config")); 

Or you will need to create the custom configuration sections you want to avoid.




回答2:


Totally untested but could you use something like this? :

ConfigurationSection exampleSection = 
    (ConfigurationSection)ConfigurationManager
                                        .GetSection("system.web/exampleSection");

Then possibly use exampleSection.ElementInformation to get more info?



来源:https://stackoverflow.com/questions/9733635/how-to-read-web-config-section-as-xml-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!