有谁知道如何使用标准 API 获取 configSource 值?
<appSettings configSource="AppSettings.config" />
或者我需要解析 XML 中的 web.config 来获取值吗?
您需要加载 AppSettingsSection,然后访问其 ElementInformation.Source 属性。
上面的链接包含有关如何访问此部分的信息。
尝试
ConfigurationManager.AppSettings["configSource"]
您需要在代码中添加:
using System.Configuration;
命名空间
需要使用@competent_tech提到的配置管理器。
//open the config file..
Configuration config= ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//read the ConfigSource
string configSourceFile = config.AppSettings.SectionInformation.ConfigSource;
无法使用 @dbugger 和 @competent_tech 的建议让 API 正确加载 AppSettings 部分。
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;
谢谢大家的指点。
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (ConfigurationSection section in config.Sections)
{
if (!string.IsNullOrEmpty(section.SectionInformation.ConfigSource))
{
Console.WriteLine("ConfigSource={0}", section.SectionInformation.ConfigSource)
// this is all your ConfigSource nodes.
}
}
您可以使用:
<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;