How to programmatically retrieve the configSource

2019-07-02 13:27发布

问题:

Does anyone know how i can get the configSource value using standard API?

<appSettings configSource="AppSettings.config" />

Or do i need to parse the web.config in XML to get the value?

回答1:

You need to load the AppSettingsSection, then access its ElementInformation.Source property.

The link above contains information about how to access this section.



回答2:

Try

  ConfigurationManager.AppSettings["configSource"]

you need to add : using System.Configuration; namespace in your code



回答3:

Need to use the config manager as @competent_tech mentioned.

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


回答4:

Couldn't get the API to correctly load the AppSettings section correctly using the suggestions from @dbugger and @competent_tech.

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

'System.Configuration.AppSettingsSection'.

Eventually went the XML route in just as many lines of code:

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;

Thanks to all for the pointers.



回答5:

You can use:

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

And retrieve the value:

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

don't forget:

using System.Configuration;


标签: c# web-config