I want to be able to get the value from a key/value pair contained within an XML configuration file, using C# .NET.
e.g.
<add key="ConnectionString" value="whatever"/>
I'm answering my own question here, but I'm interested in seeing the alternative options for loading and retrieving a value from a key/value pair from XML - perhaps there's an easier or more concise method?
ConfigurationManager Provides access to configuration files for client applications. You can fetch key/Value pair using creating custom sections and using GetSection method
<MyDictionary>
<add key="JoinG." value="[email protected]"/>
<add key="Brancheau S." value="[email protected]"/>
<add key="Cetrulo P." value="[email protected]"/>
<add key="Chiu J." value="[email protected]"/>
<add key="D'Alessio S." value="[email protected]"/>
NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("MyDictionary");
You can declare your connection string using ConfigurationManager.ConnectionStrings Property it gets the ConnectionStringsSection data for the current application's default configuration.
You can access your connection string as
string conStr = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionStringName"]);
UPDATE
To define a custom configuration file use ExeConfigurationFileMap Class
ConfigurationManager.OpenMappedExeConfiguration Method opens the client specified configuration file as system.Configuration.Configuration object .
ExeConfigurationFileMap custmConfg = new ExeConfigurationFileMap();
custmConfg.ExeConfigFilename = @"d:\test\test.XML";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(custmConfg, ConfigurationUserLevel.None);
NameValueCollection coll = (NameValueCollection)ConfigurationManager.GetSection("SectionName");
Get the configuration file, which in my case is contained in the root of my ASP.NET server application:
var doc = XDocument.Load(Server.MapPath("~") + "\\MyConfigFile.config");
Get the key/value pairs using LINQ (in the below LINQ query we are first looking for the descendants of 'add' elements, then we are looking for the first node which has a 'key' attribute matching 'ConnectionString', then we are getting the value of the 'value' attribute):
var connectionString = doc.Descendants("add")
.First(node => (string)node.Attribute("key") == "ConnectionString")
.Attribute("value").Value;
Get the value of the key specified within the square brackets:
var connectionString = parameters["ConnectionString"];
The XDocument class also contains methods for updating and saving the changes back to the physical file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With