ASP.NET Lab

The Best Web, The Best Future

博客园 首页 新随笔 订阅 管理

你可以对运行中的 ASP.NET 应用程序或 .NET 客户应用程序的配置设定进行访问。每个配置段都有属于各自的对象类型,这种情况下 C# 需要在调用 WebConfigurationManager 类的方法的同时进行类型转换。

本文的代码实例使用了非静态方法来获取配置数据。通过相同的方式你可以从任何应用程序中获取配置信息。如果你需要从代码所在的应用程序中获取配置信息,请使用静态方法 GetSection 以获得更快的执行速度。

实例

下例代码实例从应用程序 MyAppRoot 中读取 identity 元素的 impresonate 参数值。该值被显示在网页中。另外,代码中还使用了 IdentitySection 对象类型对 identity 配置段的数据进行读取。

要更改配置设定,请使用 Configuration 对象的 SaveSaveAs 方法。

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Text" %>

<script language="C#" runat="server">
    public void Page_Load()
    {
        try
        {
            // 设置包含目标 Web.config 文件的 Web 应用程序根路径
            string configPath = "/MyAppRoot";

            // 获取访问 Web.config 文件的相关配置对象。
            Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

            // 获取 <identity> 配置段的相关对象。
            IdentitySection section = (IdentitySection)config.GetSection("system.web/identity");

            // 读取 <identity> 配置段。
            StringBuilder identity = new StringBuilder();
            identity.Append("Impersonate: ");
            identity.Append(section.Impersonate.ToString());

            // 显示 <identity> 信息。
            ConfigId.Text = identity.ToString();
        }
        catch (Exception e)
        {
            ConfigId.Text = e.ToString();
        }
    }
  </script>

<html>
<head>
    <title>读取配置设定</title>
</head>
<body>
    <h2>
        读取 ASP.NET 配置
    </h2>
    <p>
        本页面显示了 ASP.NET 配置文件中 <b>identity</b> 配置段的 <b>Impersonate</b> 参数值
    </p>
    <h3>
        结果
    </h3>
    <p>
        <asp:Label
            BackColor="#dcdcdc"
            BorderWidth="1"
            ID="ConfigId"
            runat="Server" />
    </p>
</body>
</html>
posted on 2006-12-22 13:23  Laeb  阅读(335)  评论(0编辑  收藏  举报