<%@ Page Language="C#" %> <%@ Import Namespace="System.Web.Configuration" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { ConnectionStringsSection connectionStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection; string connString = WebConfigurationManager.ConnectionStrings["db"].ToString(); string dvalue = WebConfigurationManager.AppSettings["site"].ToString(); Response.Write("<br />Connection String: " + connectionStringsSection.ConnectionStrings.ToString()); Response.Write("<br />Connection String: " + connString); Response.Write("<br />Site value: " + dvalue); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Configuration Class</title> </head><body></body></html> |
你还能够以集合的方式访问区域和它们的值。列表D中的C#代码片段说明如何遍历connectioString区域中的所有值。
ConnectionStringsSection cStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection; ConnectionStringSettingsCollection cStrings = cStringsSection.ConnectionStrings; IEnumerator cStringsEnum = cStrings.GetEnumerator(); int j = 0; while (cStringsEnum.MoveNext()) { string name = cStrings[j].Name; Response.Write("<br>Name: " + name + " Value: " + cStrings[name]); j += 1; } |
结论
ASP.NET web.config文件使得开发者更方便在应用程序中保存应用程序配置。ASP.NET 2.0推出的改进简化了配置数据的恢复、存储和加密过程。虽然本文主要针对ASP.NET Web应用程序,但配置API提出的所有改进都可适用于窗体应用程序(Windows form application)。
Tony Patton拥有丰富的、VB、Lotus及XML认证方面的知识,是一个专业的应用程序开发人员。