Search code examples
c#xmlweb-configapp-config

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


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.


Solution

  • 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.