如何以编程方式从配置文件中检索configSource位置

时间:2011-12-02 03:16:15

标签: c# web-config

有谁知道如何使用标准API获取configSource值?

<appSettings configSource="AppSettings.config" />

或者我是否需要解析XML中的web.config以获取值?

5 个答案:

答案 0 :(得分:3)

您需要加载AppSettingsSection,然后访问其ElementInformation.Source属性。

上面的链接包含有关如何访问此部分的信息。

答案 1 :(得分:1)

尝试

  ConfigurationManager.AppSettings["configSource"]

您需要在代码中添加using System.Configuration;命名空间

答案 2 :(得分:1)

需要使用配置管理器作为@competent_tech提及。

//open the config file..
Configuration config= ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//read the ConfigSource
string configSourceFile = config.AppSettings.SectionInformation.ConfigSource;

答案 3 :(得分:0)

无法使用@dbugger和@comptent_tech的建议正确加载AppSettings部分的API。

Unable to cast object of type 'System.Configuration.DefaultSection' to type
     

'System.Configuration.AppSettingsSection'。

最终在几行代码中使用了XML路由:

XDocument xdoc = XDocument.Load(Path.Combine(Server.MapPath("~"), "web.config"));
var query = from e in xdoc.Descendants("appSettings")
            select e;

return query.First().Attribute("configSource").Value;

感谢所有指针。

答案 4 :(得分:-1)

您可以使用:

<appSettings>
   <add  key="configSource" value="AppSettings.config"/>
   <add  key="anotherValueKey" value="anotherValue"/>
   <!-- You can put more ... -->
</appSettings>

并检索值:

string value = ConfigurationManager.AppSettings["configSource"];
string anotherValue = ConfigurationManager.AppSettings["anotherValueKey"];

不要忘记:

using System.Configuration;