C# App.Config with array or list like data - c#

How to have array or list like information in app.config? I want user to be able to put as many IPs as possible (or as needed). My program would just take whatever specified in app.config. How to do this?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ip" value="x" />
<add key="ip" value="y" />
<add key="ip" value="z" />
</appSettings>
</configuration>
public string ip = ConfigurationManager.AppSettings["ip"];

The easiest way would be a comma separated list in your App.config file. Of course you can write your own configuration section, but what is the point of doing that if it is just an array of strings, keep it simple.
<configuration>
<appSettings>
<add key="ips" value="z,x,d,e" />
</appSettings>
</configuration>
public string[] ipArray = ConfigurationManager.AppSettings["ips"].Split(',');

You can set the type of a setting in the settings designer to StringCollection, which allows you to create a list of strings.
You can later access individual values as Properties.Settings.Default.MyCollection[x].
In the app.config file this looks as follows:
<setting name="MyCollection" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Value1</string>
<string>Value2</string>
</ArrayOfString>
</value>
</setting>

In App.config,
<add key="YOURKEY" value="a,b,c"/>
In C#,
STRING ARRAY:
string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
LIST :
List<string> list = new List<string>(InFormOfStringArray);

Related

How to Read Items into Arrays in web.config

I'm trying to build an array of strings from items in a web.config file (in IIS).
web.config
<appSettings>
<add key="favourite" value="url1; site1" />
<add key="favourite" value="url2; site2" />
<add key="favourite" value="url3; site3" />
</appSettings>
C#
// Reads first favourite into string.
public string _favourites = ConfigurationManager.AppSettings ["favourite"];
I would like each favourite to be read into string [ ] _favourites array with the semi-colon (I would parse that out later). web.config is an XML file so I can open it as one and pull the data out, but is there an easier way to do this using ConfigurationManager?
What if you add all Array values in single key like -
<appSettings>
<add key="favourite" value="url1;site1,url2;site2,url3;site3" />
</appSettings>
Read that key value as a string -
public string _favourites = ConfigurationManager.AppSettings["favourite"];
and then split the string by ','(comma) like this -
string[ ] _favouritesArr = _favourites.Split(',');
This will give all values in array _favouritesArr.
I don't know if there is a hack to do it, but I would just have one setting with multiple values;
<appSettings>
<add key="favourite" value="url1;site1;url2;site2;url3;site3;" />
</appSettings>
or
<appSettings>
<add key="favourite" value="url1=site1;url2=site2;url3=site3;" />
</appSettings>
Another solution is a separate configuration file or store this in a database.
I imagine that the favourites would change and changing web.config has consequences - it may cause your app to restart.
How about:
1.right click on project > properties
2.Navigate to settings. If it shows, This project does not have settings file. click to create one.
3.Create a SystemCollections.Speciliazed.StringCollection
4.Name it, as you want (my example StatusReason). and in end of line on e right there is ...(three) dots
5.Press them and add as much settings needed. One per line.
Sample:
Valid=979580000
Invalid=979580001
Broken=979580002
ReadyForCollect=979580003
Missing=979580004
Refine=979580005
and in web config it looks like that.
<applicationSettings>
<WebApplication.BookServices>
<setting name="StatusReason" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Valid=979580000</string>
<string>Invalid=979580001</string>
<string>Broken=979580002</string>
<string>ReadyForCollect=979580003</string>
<string>Missing=979580004</string>
<string>Refine=979580005</string>
</ArrayOfString>
</value>
</setting>
</WebApplication.BookServices>
</applicationSettings>
and get your array of strings :
var settings = Settings.Default.StatusReason;
//TODO add any logic, if needed to split
add your project reference to properties:
using WebApplication.BookServices.Properties;
and there you have a array of settings.

Dynamically add and remove key-value pairs from a section in app.config

My XML file looks like:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="databaseTypes" type="System.Configuration.NameValueSectionHandler" />
<section name="dataDictionary" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<databaseTypes>
<add key="ExampleServerPrefix_T" value="Connection_String_For_ExampleServer" />
<add key="ExampleServer2Prefix_T" value="Connection_String_For_ExampleServer_2" />
<add key="COPYLIVE_" value="ODBC;DSN=s2;" />
</databaseTypes>
<dataDictionary>
<!-- Other pairs in this section -->
</dataDictionary>
</configuration>
What I am trying to achieve is to be able to add and remove key-value pairs from the databaseTypes section. So for example to would like to dynamically add a run time a new pair <add key="blah" value="ODBC;blah" />.
First its useful to know is this possible? If so how because I can't find any relevant documentation or examples on how this is done.
Ben,
Here are two articles that will help you with adding key/value pairs to the config:
Writing custom sections to app.config
Writing custom sections into app.config
Update AppSettings and custom configuration sections in App.config at runtime
http://yizeng.me/2013/08/31/update-appsettings-and-custom-configuration-sections-in-appconfig-at-runtime/

Getting configuration values rom XML file located in the same project

I am making a little program to copy pictures form one location to another. The information for the pictures are stored in a database so I need connections string and also I create a txt file with the final output from the operation and I want to store these two values in a App.Config.xml file.
The structure of my project is very simple :
And the XML files itself is :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
<createResultFile>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</createResultFile>
</configuration>
I want to use the connectionString and <createResultFile> value in my PictureTransferTool.cs. This is my first time working with XML file and C# (.NET in general) so I want what is the way to retrieve those config values?
You config file must be like below...
Config File :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</appSettings>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>
C# :
You can read Connection String like below
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
Console.WriteLine(connectionString);
You can read User Defined Settings like Below
var Resultfile = System.Configuration.ConfigurationManager.AppSettings["ResultFile"];
Console.WriteLine(Resultfile);
The Way I normally do user-defined parameters in my app.config is i put them in the appSettings tab.
<appSettings>
<add key="myStr" value="String Value" />
and then you can access it with
string myStr = System.Configuration.ConfigurationSettings.AppSettings["myStr"];
It works for me.
Linq;
using System.Xml.XPath;
...
var doc = XDocument.Load("test.xml");// You should put the way to your XML
var name = doc.XPathSelectElements("/configuration/connectionStrings/add").Value;
var name = doc.XPathSelectElements("/configuration/createResultFile/add").Value;

Add More than One Custom Sections to App Config C#?

I would like to make an app.config that looks like
<configuration>
<SQLconneciton>
<add key=name/>
<add key= otherStuff/>
</SQLconnection>
<PacConnection>
<add key=name/>
<add key= otherStuff/>
</PacConnection>
</configuration>
I've read many examples where people make ONE custom section and add stuff, I need to allow the user to add multiple sections, read, delete. I don't really need fancy elements, just simple add and key values. Is section groups worth using or is there something easy I'm missing?
Sure - there's really nothing stopping you from creating as many custom config sections as you liked!
Try something like this:
<?xml version="1.0"?>
<configuration>
<!-- define the config sections (and possibly section groups) you want in your config file -->
<configSections>
<section name="SqlConnection" type="System.Configuration.NameValueSectionHandler"/>
<section name="PacConnection" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<!-- "implement" those config sections as defined above -->
<SqlConnection>
<add key="abc" value="123" />
</SqlConnection>
<PacConnection>
<add key="abc" value="234" />
</PacConnection>
</configuration>
The System.Configuration.NameValueSectionHandler is the default type to use for a config section that contains <add key="...." value="....." /> entries (like <appSettings>).
To get the values, just use something like this:
NameValueCollection sqlConnConfig = ConfigurationManager.GetSection("SqlConnection") as NameValueCollection;
string valueForAbc = sqlConnConfig["abc"];
And you can absolutely mix and match existing section handler types as defined by .NET as well as your own custom config sections, if you've defined some of those yourself - just use whatever you need!

c# Application Configuration File: AppSettings Reads Empty?

This is my first time using an XML config file. In the solution explorer I right click, add, new item, application config. file.
I then edited the file to read...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key1" value="1000" />
</appSettings>
</configuration>
...and tried to access it with...
Int32.Parse(ConfigurationManager.AppSettings.Get("Key1"));
...but it says that the parameter is null. I looked at just ConfigurationManager.AppSettings and it's AllKeys property has dimension 0.
What am I doing wrong?
Thanks!
Right-click on your project, choose Properties>Settings tab and edit your settings there because the config file is not the only place these values are stored at.
In your code use Settings.Default.MySetting to access the settings.
You'll need to add using MyProjectName.Properties; to your using statements in order to access the settings this way or you'll have to fully qualify it as MyProjectName.Properties.Settings.Default.MySetting...
I know this is super old but I just encountered this opening an old project. A reference to System.Configuration was missing.
To ensure get information from App.config using ConfigurationManager.AppSettings["<Key name>"]; be sure to set your values inside <appSettings> section.
Example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key ="IntervalSeconds" value ="60000"/>
<add key ="OutputPathLog" value ="\\myserver\hackingtrack\Projects\Log\"/>
<!--Jorgesys si Elenasys sunt puisori-->
<add key="InputFeeds1" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds2" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds3" value="https://cld.blahbla.com//portadaKick.json" />
</appSettings>
</configuration>
Retrieving values:
string intervalSeconds = ConfigurationManager.AppSettings["IntervalSeconds"];
string inputFeeds1 = ConfigurationManager.AppSettings["InputFeeds1"]; ;
string inputFeeds2 = ConfigurationManager.AppSettings["InputFeeds2"];
string inputFeeds3 = ConfigurationManager.AppSettings["InputFeeds3"];

Categories