Hi i have the following app.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="DayTime" value="08-20" />
<add key="NightTime" value="20-08" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
<add key="GridMode" value="1"/>
</appSettings>
I need to read all the keys at one shot and store it some where like Dictionary.
I have tried following code but give me null value
with exception Cannot convert Keyvalueinternalcollection to hashtable
var section = ConfigurationManager.GetSection("appSettings") as Hashtable;
How to read all keys with their values ?
Hashtable version.
Hashtable table = new Hashtable((from key in System.Configuration.ConfigurationManager.AppSettings.Keys.Cast<string>()
let value= System.Configuration.ConfigurationManager.AppSettings[key]
select new { key, value }).ToDictionary(x => x.key, x => x.value));
Comment to other answers
System.Configuration.ConfigurationManager.AppSettings is predefined 'appSettings' section, use it.
Do not cast to Hashtable but to IEnumerable instead:
var section = ConfigurationManager.GetSection("appSettings");
foreach (var kvp in section as IEnumerable)
{
//TODO
}
I think you can do something like this:
var loc=(NameValueCollection)ConfigurationSettings.GetSection("appSettings");
var dic=new Dictionary<string,string>();
foreach (var element in loc.AllKeys)
{
dic.Add(element, loc[k]);
}
var section = ConfigurationManager.GetSection("appSettings")
should suffice.
Related
I have created custom tags in web.config file.These values am storing in a hash table.After storing in the hash table am reading both key and value am able to read the key but not the value.Here is my code in web.config
<configSections>
<sectionGroup name="BlockIpSection">
<section name="ipslist" type="CustomConfigurationHandler.CustomConfiguration, CustomConfigurationHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere"/>
</sectionGroup>
</configSections>
<BlockIpSection>
<ipslist>
<ipaddress1 value="100"></ipaddress1>
<ipaddress2></ipaddress2>
</ipslist>
</BlockIpSection>
Here there are 2 tags section group name and section name.I have created the tags as ipaddress1 and ipaddress2.Am storing value 100 to ipaddress1 tag.
I am reading this web.config like this
Hashtable config = (Hashtable)ConfigurationManager.GetSection("BlockIpSection/ipslist");
foreach (string key in config.Keys)
{
Response.Write(key + "<br>");
}
Tags from web.config we are storing in hashtable and reading using key.when i use config[key] to read the value its giving error.
Try to use
App.BlockIpSection
or
ConfigurationManager.AppSettings["BlockIpSection"]
Define your keys and values in web. config. like this .
<BlockIpSection>
<ipslist>
<add key="ipaddress1 " value="100"/>
<add key="ipaddress2 " value="100"/>
// IP keys and values ....
</ipslist>
</BlockIpSection>
Hashtable config = (Hashtable)ConfigurationManager.GetSection("BlockIpSection/ipslist");
foreach (DictionaryEntry dicEntry in config)
//OR
// foreach (KeyValuePair<string,string> dicEntry in config)
{
string key = Convert.ToString(dicEntry.Key);
string val = Convert.ToString(dicEntry.Value);
// Your code goes here
}
first of all, you need to mention key and value for both tags in web.config and then
Use NameValueCollection instead of Hashtable.
problem with Hashtable is given below:
try this Block of code:
NameValueCollection nvObj = new NameValueCollection();
nvObj = ConfigurationManager.GetSection("MyCustomSettings") as NameValueCollection;
Response.Write(hs["key1"] + "</br>");
I have an app.config file like this:-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="botLogs" value="d:\TFS Projects-BotLogs/"/>
<add key="botfolder" value="C:\BOTSCONFIG"/>
</appSettings>
<connectionStrings>
<add connectionString="Server=1.1.1.1;Database=BGAppCrawling;UID=sa;Password=something;" name="VGDB"/>
<add connectionString="Server=1.1.1.1;Database=BGMappingStaging;UID=sa;Password=something;" name="VGDBMapping"/>
</connectionStrings>
</configuration>
Now I can fetch values based on keys in appSettings section like this:-
string filePath = ConfigurationSettings.AppSettings["botLogs"].ToString();
But what is the way if I want to fetch key based on values from appSetting section ?
foreach(string key in System.Configuration.ConfigurationSettings.AppSettings)
{
var key = key.ToString();
var value = ConfigurationSettings.AppSettings[key.ToString()];
//Do something here
}
or
var settings = System.Web.Configuration.ConfigurationSettings.AppSettings;
var value = from string k in settings.Keys
where k.StartsWith("MyValue")
select settings[k];
foreach (string key in Configuration.AppSettings.Settings.AllKeys)
{
string value = appSettings.Settings[key].Value;
if (value.Equals(myValue))
{
Console.WriteLine("Found Key: " + key);
break;
}
}
i would say that you should replace your keys with values and the values with the keys,
<add key="d:\TFS Projects-BotLogs/" value="botLogs"/>
<add key="C:\BOTSCONFIG" value="botfolder"/>
thanks
rakesh
You can try following GetEnumerator method based code :
NameValueCollection values = ConfigurationManager.AppSettings;
Iterate(values);
public void Iterate(NameValueCollection myCollection)
{
IEnumerator myEnumerator = myCollection.GetEnumerator();
Console.WriteLine("KEY VALUE");
foreach (String item in myCollection.AllKeys)
Console.WriteLine(" {0,-10} {1}", item, myCollection[item]);
Console.WriteLine();
}
I have a simple program that would let the user add a section to a custom config file, it would have more settings than what is shown. I populate a datagridview with a list of all configurations. My problem is, the method to populate the listbox wouldn't know all the names of the sections that the user may have added, I'm trying to be dynamic. Is there an easy way to loop through these sections and get their names? Or do I have to make a Section, Collection, and Elements in order to to this?
Thanks.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="Jason" type="SQLQueryOutput.SQLQueryOutputConfigSection, SQLQueryOutput, Version=1.0.0.0, Culture=neutral, PublicKeyToken=760d257b40400289" />
<section name="Steve" type="SQLQueryOutput.SQLQueryOutputConfigSection, SQLQueryOutput, Version=1.0.0.0, Culture=neutral, PublicKeyToken=760d257b40400289" />
</configSections>
<Jason OutputFilePath="C:\temp\jason.txt" />
<Steve OutputFilePath="C:\temp\steve.txt" />
</configuration>
How about using Linq To Xml to parse your config file. For example,
var xDoc = XDocument.Load(configFile);
var sections = xDoc.XPathSelectElements("//configSections/section")
.Select(x=>x.Attributes().ToDictionary(a=>a.Name,a=>a.Value))
.ToList();
var name = sections[0]["name"];
or
var outputFilePaths = xDoc.Root.Elements()
.Where(d => d.Name.LocalName != "configSections")
.ToDictionary(e => e.Name.LocalName, e => e.Attribute("OutputFilePath").Value);
Actually your configSections element can contain sectionGroup elements also. With Linq to Xml:
XDocument xdoc = XDocument.Load(config_file_path);
var names = xdoc.Root.Element("configSections")
.Descendants("section") // selects also sectionGroup/section
.Select(s => (string)s.Attribute("name"));
suppose I have the following XML:
<appSettings>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
<add key="key3" value="value3" />
<add key="key4" value="value4" />
</appSettings>
and I would like to transform it to an object like:
AppSettings["key1"] = "value1";
AppSettings["key2"] = "value2";
AppSettings["key3"] = "value3";
and so forth …
I've looked it up on the internet and haven't found yet something useful. Can someone help me out on this ?
Easy.
var xd = XDocument.Parse(xml);
var AppSettings = xd.Root.Elements("add")
.ToDictionary(
xe => xe.Attribute("key").Value,
xe => xe.Attribute("value").Value);
You could do this with LINQ quite easily:
XElement appSettings = (...); // Parse your XML and get the root Element.
var dict = appSettings.Elements().ToDictionary(el => el.Attribute("key"), el => el.Attribute("value"));
var xml = XDocument.Parse("<appSettings><add key=\"key1\" value=\"value1\" /> <add key=\"key2\" value=\"value2\" /> <add key=\"key3\" value=\"value3\" /> <add key=\"key4\" value=\"value4\" /> </appSettings>");
xml.Elements().First().Elements()
.Select (x => new { key = x.Attribute("key").Value, value = x.Attribute("value").Value })
.ToDictionary(e => e.key, e => e.value).Dump();
Am trying to implement a generic way for reading sections from a config file. The config file may contain 'standard' sections or 'custom' sections as below.
<configuration>
<configSections>
<section name="NoteSettings" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<appSettings>
<add key="AutoStart" value="true"/>
<add key="Font" value="Verdana"/>
</appSettings>
<NoteSettings>
<add key="Height" value="100"/>
<add key="Width" value="200"/>
</NoteSettings>
The method that I tried is as follows :
private string ReadAllSections()
{
StringBuilder configSettings = new StringBuilder();
Configuration configFile = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
foreach (ConfigurationSection section in configFile.Sections)
{
configSettings.Append(section.SectionInformation.Name);
configSettings.Append(Environment.NewLine);
if (section.GetType() == typeof(DefaultSection))
{
NameValueCollection sectionSettings = ConfigurationManager.GetSection(section.SectionInformation.Name) as NameValueCollection;
if (sectionSettings != null)
{
foreach (string key in sectionSettings)
{
configSettings.Append(key);
configSettings.Append(" : ");
configSettings.Append(sectionSettings[key]);
configSettings.Append(Environment.NewLine);
}
}
}
configSettings.Append(Environment.NewLine);
}
return configSettings.ToString();
}
Assuming that all custom sections will have only KEY-VALUE
Is such an implementation possible? And if yes, is there a 'cleaner' and more elegant solution than this one?
The above method also reads 'invisible' sections like mscorlib, system.diagnostics. Is this avoidable?
System.Data.Dataset returns a dataset which could not be cast to a NameValueCollection. How can this be handled?
Corrections/suggestions welcome.
Thanks.
Since configuration file is XML file, you can use XPath queries for this task:
Configuration configFile = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
XmlDocument document = new XmlDocument();
document.Load(configFile.FilePath);
foreach (XmlNode node in document.SelectNodes("//add"))
{
string key = node.SelectSingleNode("#key").Value;
string value = node.SelectSingleNode("#value").Value;
Console.WriteLine("{0} = {1}", key, value);
}
If you need to get all {key, value} pair then you need to define triplets of XPath queries:
1 - main query for selecting nodes with similar structure. 2, 3 - queries for extracting key and value nodes from nodes retrieved by first query. In your case it's enough to have common query for all nodes, but it's easy to maintain support for different custom sections.
Read your config into a XmlDocument then use XPath to find the elements your looking for?
Something like;
XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("~/web.config"));
XmlNodeList list = doc.SelectNodes("//configuration/appSettings");
foreach (XmlNode node in list[0].ChildNodes)
...
You can read a custom section as follows:
var sectionInformation = configuration.GetSection("mysection").SectionInformation;
var xml = sectionInformation.GetRawXml();
var doc = new XmlDocument();
doc.LoadXml(xml);
IConfigurationSectionHandler handler = (IConfigurationSectionHandler)Type.GetType(sectionInformation.Type).GetConstructor(new Type[0]).Invoke(new object[0]);
var result = handler.Create(null, null, doc.DocumentElement);
When you've specified the NameValueSectionHandler as the type attribute for a section and call to Configuration.GetSection(string), you will receive a DefaultSection instance as the return type.
string SectionInformation.SectionInformation.GetRawXml() is the key in this case to get into your data.
I answered another similar question with a valid way to do it using System.Configuration that you can reference to get all the details and a code snippet.
NameValueSectionHandler can i use this section type for writing back to the app