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();
}
Related
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.
I have an XML file with a structure and trying to get value from "Key" and "Value":
<appSettings>
<add key="Url" value=" http://book.jetstar.com/"/>
<!--Id's or Xpath-->
<add key="Origin" value="somevalue"/>
<add key="Destination" value="somevalue"/>
<add key="Adult" value ="somevalue" />
<add key="somevalue"/>
<!--Controls-->
<add key="OriginCtrl" value=" Input"/>
<!--Textbox-->
<add key="DestinationCtrl" value=" Input"/>
<add key="AdultCtrl" value=" Select"/>
<add key="SearchFlightsCtrl " value=" Button"/>
</appSettings>
I am trying to create a loop that loops through the XML and get value of these "key" and "value". The code I am writing is
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList xmlnodelist;
string keyname = "";
string keyvalue = "";
xmlDoc.Load(filename);
xmlnodelist = xmlDoc.SelectNodes("appSettings");
foreach (XmlNode nodes in xmlnodelist)
{
keyname = nodes.Attributes.GetNamedItem("key").Value;
keyvalue = nodes.Attributes.GetNamedItem("value").Value;
}
The error with "object not set to an instance" rises when i try to run this piece of code. I wonder if there is errors in the code where getting the Value. Any advices would be appreciated.
Since you want to get appSettings childs you should be using
xmlDoc.SelectNodes("appSettings/add");
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 this app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="domain" value="localhost"/>
<add key="hostname" value="hostpc"/>
</appSettings>
</configuration>
I am using this LINQ to XML query to get the value of key named "domain". For instance, when i say i want to get value of key named "domain" it should give me "localhost" :
var domain = (from appNode in xmlElement.Elements("add")
where appNode.Attribute("key").Value == "domain"
select appNode.Attribute("value"));
But my query is missing something can anyone identify what i am missing or how it can be made better, it doesn't work at the moment.
Note: I only want to use linq to xml
I used your app.config file content as it is, write a small console based application with following code:
class Program
{
static void Main(string[] args)
{
// Create the query
var nodes = from appNode in XElement.Load("App.config").Descendants("appSettings").Elements()
where appNode.Attribute("key").Value == "domain"
select appNode;
var element = nodes.FirstOrDefault();
string value = element.Attribute("value").Value;
Console.WriteLine(value);
//Pause the application
Console.ReadLine();
}
}
The output is: localhost
Hope this helps. If it does not work on your machine, please share error details.
try using this one:
XElement doc = XElement.Load("ConsoleApplication1.exe.config");
var domain = (from appNode in doc.Element("appSettings").Elements("add")
where appNode.Attribute("key").Value == "domain"
select appNode.Attribute("value").Value).FirstOrDefault();
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