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

C# 如何以编程方式从配置文件检索configSource位置,c#,web-config,C#,Web Config,有人知道如何使用标准API获取configSource值吗 <appSettings configSource="AppSettings.config" /> 或者我需要用XML解析web.config来获取值吗?试试看 ConfigurationManager.AppSettings["configSource"] 您需要添加:使用System.Configuration代码中的命名空间您可以使用: <appSettings> <add key

有人知道如何使用标准API获取configSource值吗

<appSettings configSource="AppSettings.config" />

或者我需要用XML解析web.config来获取值吗?

试试看

  ConfigurationManager.AppSettings["configSource"]
您需要添加:
使用System.Configuration代码中的命名空间

您可以使用:

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

using System.Configuration;
您需要加载,然后访问其ElementInformation.Source属性


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

需要将配置管理器用作@competable\u tech

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

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

“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;

感谢大家的指点。

那么我如何访问AppSettings.config中的键呢?ASP.NET会加载外部配置文件吗?我不明白你的意思。是否要加载AppSettings.config文件?您可以将应用程序的一些值或全局参数放入AppSettings部分,然后检索这些值。我编辑了上一篇文章。很抱歉,我的OP中可能不清楚。NET配置允许您在外部文件中引用和存储配置数据。我所有的appSettings密钥都在外部文件中。是的,我知道。似乎这段代码只在EXE上下文中有效。你知道如何让它在ASP.NET环境下工作吗?当然……配置config=ConfigurationManager.OpenExeConfiguration(Path.Combine(Server.MapPath(“~”,“web.config”));
Unable to cast object of type 'System.Configuration.DefaultSection' to type
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;