如何以编程方式读取web.config值?

时间:2011-08-29 13:42:22

标签: c# asp.net web-config

我使用asp.net和c#4。 我有一个Web.Config文件

<globalization culture="auto:fr" uiCulture="fr"/>

我想在Code Behind中以编程方式在新变量中获取此值。

var test = .......

如何获得文化价值?

解决方案感谢您的回答:

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
GlobalizationSection section = (GlobalizationSection)config.GetSection("system.web/globalization");

OpenWebConfiguration("/"); // Point to Physical path for the Web.Config file (Useful when using Routing).

GetSection("system.web/globalization"); // Get the globalization section within the system.web node.

3 个答案:

答案 0 :(得分:7)

这是一个GlobalizationSection,所以你可以通过

获得它
var globalizationSection = 
        WebConfigurationManager.GetSection("globalization") as GlobalizationSection;

答案 1 :(得分:2)

您可能需要导入System.Configuration和System.Web.Configuration命名空间才能执行此操作,但您可以执行以下操作:

//and here is the code to get the section
Configuration config = WebConfigurationManager.OpenWebConfiguration("/");     
GlobalizationSection section = config.GetSection("globalization") as GlobalizationSection;

答案 2 :(得分:0)