How to Read Items into Arrays in web.config - c#

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.

Related

C# App.Config with array or list like data

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);

Adding and reading a custom section in AppSettings in C#

I hope you can help me.
I'm supposed to add a new type of values to an AppSettings file (already existing with some values). Those values are a whole list of special folders so I thought the best way would be to have a new section for those folder values so that the file would look like this:for
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="usPath" value="folderName1" />
<add key="tcPath" value="folderName2" />
<add key="usGUID" value="folderID1" />
<add key="tcGUID" value="folderID2" />
</appSettings>
<updateFolders>
<add key="folderID3" value="folderName3">
<add key="folderID4" value="folderName4">
</updateFolders>
</configuration>
Reading and writing within the already existing appSettings-tag is no problem but I haven't find a way yet to modify the updateFolders section. I'm really new to using AppSettings in this way so I don't know too much about what's possible and what's not. In addition to that I think the AppSettings file might have been set up in a wrong way from the very beginning (it gets created by using a System.IO.File-Writer).
see ConfigurationManager.GetSection
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection(v=vs.110).aspx

MVC 4 dedicated configuration file

I have to add some constants to MVC 4 project.
Adding them to in web.config will work:
<appSettings>
<add key="MyConst1" value="123"/>
<add key="MyConst2" value="321"/>
<add key="MyConst3" value="234"/>
</appSettings>
Is there a way to create separate config file for this constants?
I guess you want to separate your appSettings from web.config, you can store them in a separate file and then specify that in your web.config under appSettings's configSource like:
<appSettings configSource="MySettings.config" />
and then you can have your settings in MySettings.config as:
<?xml version="1.0" encoding="UTF-8"?>
<appSettings>
<add key="MyConst1" value="123"/>
<add key="MyConst2" value="321"/>
<add key="MyConst3" value="234"/>
</appSettings>
You may see: Using configSource to split configuration files
If you put your code snippet in a file called appSettings.config, you can simply reference that file in your web config:
<appSettings configSource="appSettings.config" />

Reading connection string from external config file

I have created a console application and an app.config file and Connections.config file.
The app.config file has a connectionstring property source pointing to the Connections.config
When I tried to read the connection string in the application, I get a ConfigurationErrorException
This is my main method.
static void Main(string[] args)
{
var settings = ConfigurationManager.ConnectionStrings;
if (settings != null)
{
foreach (ConnectionStringSettings setting in settings)
{
Console.WriteLine(setting.ConnectionString);
}
}
}
App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="Connections.config"></connectionStrings>
</configuration>
Connections.config file
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Here I observed two things.
First: If I specify configSource I am unable to read the connection string (throwing exception.)
Second: If I put same connection string in App.config file and tried to read then the code is working but getting two connection string (which supposed to be return only one which is empty string)
The first connection string is sqlexpress connection string like this
data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
second connection string it returning is empty string (This is expected).
I want to read connection string from external file like in my scenario. How to do that? What am I missing here?
MSDN says:
Do not include any additional elements, sections, or attributes.
You need to remove the XML encoding.
Edit
Also, you need to set the properties of your config file to Copy to Output Directory = Copy if newer or Copy always.
Edit 2
To build on what Dave said, you add the clear element to your external file. Your final Connections.config file should look exactly like this:
<connectionStrings>
<clear/>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Your Connections.config file should be as shown below without the xml header
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Also for it to correctly locate the file in your console application, please set the Copy to Output Directory to Copy Always or Copy If Newer.
That first connection string you are getting is inherited from the machine.config. This is described in the MSDN documentation. http://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.90).aspx
You can use the Clear tag in your config file to remove inherited connection strings.
http://msdn.microsoft.com/en-us/library/ayb15wz8(v=vs.90).aspx
<connectionStrings>
<clear/>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
There is a nice article on MSDN: https://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx.
Quote from the article:
To store connection strings in an external configuration file, create
a separate file that contains only the connectionStrings section. Do
not include any additional elements, sections, or attributes. This
example shows the syntax for an external configuration file.
<connectionStrings>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Hope this helps people who run into this question later.

web.config c# .net web application

How to read a personal section in a web.config ?
<MyPersonalSection>
<add name="toto" enable="true" URL="http://localhost:43242" />
<add name="titi" enable="false" URL="http://localhost:98762" />
<MyPersonalSection/>
I'd like to get the enable value and/or URL value with the name value.
I also have this mistake : Unrecognized configuration section MyPersonalSection
I been trying
var config = ConfigurationManager.GetSection("MyPersonalSection");
Here is a cool example for that.
You don't need to write a custom configuration handler to get what you want. There are built-in configuration handlers that you can use if you simply want key-value entries. But, you'll have to use key instead of name and value instead of URL. For example:
<configuration>
<configSections>
<section name="MyPersonalSection" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MyPersonalSection>
<add key="toto" value="http://localhost:43242" />
<add key="titi" value="http://localhost:98762" />
</MyPersonalSection>
</configuration>
And you can access them via code:
var myValues = ConfigurationSettings.GetConfig("MyPersonalSection") as NameValueCollection;
var url = myValues["toto"];
I would suggest naming your keys in a way that makes it clear what the value should be, like "totoUrl" and "titiUrl".
If you want something other than string value pairs, you'll have to write your own custom handler.
You can add appSettings section in your web.config with key that you will need. For example:
<configuration>
<appSettings>
<add key="FirstUrl" value="http://localhost:43242"/>
<add key="SecondUrl" value="http://localhost:98762" />
</appSettings>
...
</configuration>
So, since aspx.cs file, you can declare directive
using System.Configuration;
And later, you can retrieve FirstUrl value in this way:
var myUrl = ConfigurationManager.AppSettings["FirstUrl"];

Categories