read whole settings section instead of one by one - c#

I have a app.config looking like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="Setting1" value="value1" />
<add key="Setting2" value="value2" />
</appSettings>
</configuration>
Is it possible to somehow read the whole section of settings? Instead of just calling them one by one:
private static readonly string Setting1 = ConfigurationManager.AppSettings["Setting1"];
private static readonly int Setting2 = ConfigurationManager.AppSettings["Setting2"];
Is that possible? If not by this way, how should I achieve this (was thinking about creating an own Settings.xml but I wanna try this first).

Just directly use the object returned by ConfigurationManager.AppSettings: it has a whole load of other members.
eg.
var as = ConfigurationManager.AppSettings;
foreach (string k in as.AllKeys) {
Console.WriteLine("{0}: {1}", k, as[k]);
}

Related

Custom section in App.Config, ConfigurationManager stops working

I have created a console app in c# that reads information from App.config. if i add things in appSettings section, i can acces them and it works, but as soon as i add some custom sections i cant read anything from it. I am using ConfigurationManager, and i have the reference for it included.
My app config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
and i am trying to acces those information like this:
string path = ConfigurationManager.AppSettings["path"];
var settings = ConfigurationManager.GetSection("ImageFormatsINeed");
When i didnt have the ImageFormatsINeed section i could get the path from AppSettings and it was working. But as soon as i added my ImageFormatsINeed section, everything stops working.
Now my question is how can i add custom sections in app.config that it will work, or should i just read my ImageInformation from some custom xml file or config file?
You have to use the tag <configSections> at the top in your app.config, for this case you should use the type AppSettingsSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
Then in your C# code:
NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);

App.Config setting to ComboBox

Here below is App.Config Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="DBServer" value="Localhost"/>
<add key="DBServer" value="Sql2005rs"/>
<add key="DBName" value="Everest"/>
</appSettings>
</configuration>
I Am trying to get the values Local Host and Sql2005rs to return in a combo box this is what I'm using can anyone tell me why it is failing.
public Form1()
{
InitializeComponent();
var DBServerNames = ConfigurationManager.AppSettings.AllKeys .Where(key => key.StartsWith("DBServer")) .Select (key => ConfigurationManager.AppSettings[key]) .ToArray();
DBServer.Items.AddRange(DBServerNames);
}
Yet it only return sql2005rs anyone know why?
You will always get the last one when you have multiple settings with the same key. When you have multiple of the same key each one gets overridden by the next.
So rather than do that, which really isn't a very good thing to do - the key is supposed to be unique, as in any key/value dictionary - change your settings to something like :
<appSettings>
<add key="DBServers" value="Localhost,Sql2005rs"/>
<add key="DBName" value="Everest"/>
</appSettings>
Then just pluck out the DBServers value and parse that. Something like:
string[] myServers= ConfigurationManager.AppSettings["DBServers"].Split(',');

Window service generates exception while reading 'ConfigurationManager.AppSettings["FilePath"].ToString()'

I am making a windows service.
It contain one App.config file as below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SQLConnectionStr" value="Data Source=192.168.1.116;Initial Catalog=Conezone;User Id=sa;Password=saadmin#123;"/>
<add key="FilePath" value="D:\Autoparts Guru\LINES2\"/>
</appSettings>
</configuration>
To get FilePath value in service code, I am writing
ConfigurationManager.AppSettings["FilePath"].ToString()
But it generates NullReferenceException.
Hope i get the answer quickly.
This code may help you:
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="SQLConnectionStr" value="Data Source=000.000.000.000;Initial Catalog=mydb;User Id=sa;Password=sa;"/>
<add key="FilePath" value="myfilepath"/>
</appSettings>
</configuration>
Namespace
using System.Configuration;
Code:
string filepath = string.Empty;
filepath = ConfigurationManager.AppSettings["FilePath"];

Reading keyvalue pairs into dictionary from app.config configSection

I currently have an app.config in an application of mine set up like so:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="DeviceSettings">
<section name="MajorCommands" type="System.Configuration.DictionarySectionHandler"/>
</sectionGroup>
</configSections>
<appSettings>
<add key="ComPort" value="com3"/>
<add key="Baud" value="9600"/>
<add key="Parity" value="None"/>
<add key="DataBits" value="8"/>
<add key="StopBits" value="1"/>
<add key="Ping" value="*IDN?"/>
<add key="FailOut" value="1"/>
</appSettings>
<DeviceSettings>
<MajorCommands>
<add key="Standby" value="STBY"/>
<add key="Operate" value="OPER"/>
<add key="Remote" value="REMOTE"/>
<add key="Local" value="LOCAL"/>
<add key="Reset" value="*RST" />
</MajorCommands>
</DeviceSettings>
</configuration>
My current objective is to foreach or simply read all values from MajorCommands into a Dictionary<string, string> formatted as Dictionary<key, value>. I've tried several different approaches using System.Configuration but none seem to work and I haven't been able to find any details out there for my exact question. Is there any proper way to do this?
using ConfigurationManager class you can get whole section from app.config file as Hashtable which you can convert to Dictionary if you want to:
var section = (ConfigurationManager.GetSection("DeviceSettings/MajorCommands") as System.Collections.Hashtable)
.Cast<System.Collections.DictionaryEntry>()
.ToDictionary(n=>n.Key.ToString(), n=>n.Value.ToString());
you'll need to add reference to System.Configuration assembly
You are almost there - you just have nested your MajorCommands a level too deep. Just change it to this:
<configuration>
<configSections>
<section
name="MajorCommands"
type="System.Configuration.DictionarySectionHandler" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<MajorCommands>
<add key="Standby" value="STBY"/>
<add key="Operate" value="OPER"/>
<add key="Remote" value="REMOTE"/>
<add key="Local" value="LOCAL"/>
<add key="Reset" value="*RST" />
</MajorCommands>
</configuration>
And then the following will work for you:
var section = (Hashtable)ConfigurationManager.GetSection("MajorCommands");
Console.WriteLine(section["Reset"]);
Note that this is a Hashtable (not type safe) as opposed to a Dictionary. If you want it to be Dictionary<string,string> you can convert it like so:
Dictionary<string,string> dictionary = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);
I would probably treat the config file as an xml file.
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load("app.config");
XmlNodeList majorCommands = document.SelectNodes("/configuration/DeviceSettings/MajorCommands/add");
foreach (XmlNode node in majorCommands)
{
myDictionary.Add(node.Attributes["key"].Value, node.Attributes["value"].Value)
}
If document.Load doen't work, try converting your config file to xml file.

Count the no of keys in appconfig in a class file

I need to know how to count the no of keys in app settings and manipulate through them in class file...
For example I'll have my app config as follows
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Mysqlrateteller" value="server=localhost;Database=rateteller;User Id=root;Password=;"/>
<add key="Mysqlrateteller1" value="server=localhost;Database=rateteller1;User Id=root;Password=;"/>
<add key="Mysqlrateteller2" value="server=localhost;Database=rate;User Id=root;Password=;"/>
</appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Here i may have n no of keys. And i need to count the no of keys available in a class file of this project. how to do it?
You can do like this:
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
int cntAppSettingKeys = appSettings.Count;
AppSettings is a NameValueCollection. So below code will work
System.Configuration.ConfigurationManager.AppSettings.Count

Categories

Resources