- A Word on the Metabase
- Walk-Through of web.config's Hierarchical Structure
- System.Configuration and System.Web.Configuration Namespaces
- Accessing web.config Using System.Xml
- Chapter Summary
Accessing web.config Using System.Xml
As a web developer, you might have been called late in the evening (or extremely early in the morning) to support a failing web application. At those times, genius can strike: What if I had a tool that I could look at the configuration information?
Alas, the web.config file is not viewable by directly navigating to it. However, it isn't difficult to develop a quick application that displays the contents of the web.config file through the browser.
Because web.config is simply an XML file, it's easy to use the classes found in the System.Xml class to load the document and read or manipulate its contents. Listing 7.15 shows the code that is used to develop a simple viewer utility to view the contents of the web.config file.
Potential Security Risk
Exposing the web.config file externally could pose security risks. Be sure to thoroughly examine your security policy before implementing this example.
Listing 7.15 Viewing web.config Using the System.Xml Classes
Imports System.Xml Public Class configviewer Inherits System.Web.UI.Page #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load Dim reader As XmlTextReader reader = New XmlTextReader(Server.MapPath("web.config")) Dim doc As XmlDocument = New XmlDocument() doc.Load(reader) Dim writer As XmlTextWriter = New
XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8) doc.WriteTo(writer) writer.Flush() writer.Close() reader.Close() End Sub End Class
This example uses the Server.MapPath method to map the physical path to the web.config file found in the same directory as the .aspx source code file. The XmlTextReader class loads the contents into an XmlDocument object, which then writes its contents to an XmlTextWriter class. The XmlTextWriter writes directly to the Response stream, and the XML is displayed in the browser.
For more information on using System.Xml, see Chapter 6, "Exploring the System.XML Namespace."