3

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Ciaran Gallagher
  • 3,895
  • 9
  • 53
  • 97
  • Have you not heard of the `System.Configuration` namespace and the `ConfigurationManager` class? – Brian Warshaw Jan 06 '14 at 13:38
  • Are you trying to earn the [Self-Learner](http://stackoverflow.com/help/badges/14/self-learner) badge? :-) – Rui Jarimba Jan 06 '14 at 13:47
  • @RuiJarimba Never heard of it but it is good to learn :) – Ciaran Gallagher Jan 06 '14 at 13:53
  • @BrianWarshaw, I tried using it before but I didn't really know how to use it. Perhaps you could enlighten me? (and anyone else who comes across this question). – Ciaran Gallagher Jan 06 '14 at 13:54
  • Reading from a configuration file has been [asked and answered](https://www.google.com/search?q=c%23+configuration+file+site:stackoverflow.com) many times over... – Metro Smurf Jan 06 '14 at 14:39
  • @MetroSmurf, none of the answers you provided there answer my question. My particular question has not been answered adequately previously, I've already looked. There are definitely similar questions and lots of things which help, but I was unable to find anything exactly for what I was looking for. – Ciaran Gallagher Jan 06 '14 at 21:24

2 Answers2

2

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="Gabriel.Boltniew@xxxx.com"/>
        <add key="Brancheau S." value="Steve.sd@xxxx.com"/>
        <add key="Cetrulo P." value="Paul.ds@xxxx.com"/>
        <add key="Chiu J." value="ds.Chiu@xxxx.com"/>
        <add key="D'Alessio S." value="dsd.sdd@ffdf.com"/>

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");
Suraj Singh
  • 4,041
  • 1
  • 21
  • 36
  • Does the ConfigurationManager get the default config file for the application? In my case, I'm looking to open a custom XML configuration file, so how would that work using the ConfigurationManager? Also, I'm not sure if the ConnectionStrings property applies here, as my connection string isn't stored within an ASP.NET element, and it's not within my web.config file. – Ciaran Gallagher Jan 06 '14 at 14:22
  • Thanks for the update, that looks like it will work nicely. Does the ConfigurationManager allow for changes to be made to the configuration? If so, are the changes to the physical file, or do they only exist in the server or session instance of the web application? – Ciaran Gallagher Jan 06 '14 at 15:07
  • 1
    @CiaranGallagher BTW nice question , i think this link will will provide you a better answer http://stackoverflow.com/questions/4216809/configurationmanager-doesnt-save-settings – Suraj Singh Jan 06 '14 at 15:35
1

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.

Ciaran Gallagher
  • 3,895
  • 9
  • 53
  • 97