C#
System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot"); System.Configuration.ConnectionStringSettings connString; if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count) { connString = rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"]; if (null != connString) Console.WriteLine("Northwind connection string = \"{0}\"", connString.ConnectionString); else Console.WriteLine("No Northwind connection string"); }
编译代码
此示例需要:
-
根 Web.config 文件中的 connectionStrings 元素,其中包含名为 NorthwindConnectionString 的连接。该元素可能如下所示:
connectionStrings 元素是 元素的直接子级,并且是 system.web 元素的对等项。