I’ll show how to parse comma-separated integer values from app.config and load them into a HashSet for efficient lookups. First, take a look at the setting (retryStatusCodes) in app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="retryStatusCodes" value="408,429,503"/>
</appSettings>
</configuration>
Code language: HTML, XML (xml)
To load and parse this setting from app.config, do the following:
- Get the setting from app.config with ConfigurationManager.AppSettings.
- Split the comma-separated string, giving you an array of string values.
- Loop over the string values and parse them into integers with int.Parse().
- Add the integers to a HashSet for later use.
The following code shows how to do this:
using System.Configuration;
using System.Linq;
var csv = ConfigurationManager.AppSettings["retryStatusCodes"];
var errorCodes = csv.Split(',').Select(i => Int32.Parse(i));
var retryStatusCodes = new HashSet<int>(errorCodes);
Console.WriteLine($"We have {retryStatusCodes.Count} retry status codes");
Console.WriteLine($"Retry when status code is 404? {retryStatusCodes.Contains(404)}");
Console.WriteLine($"Retry when status code is 429? {retryStatusCodes.Contains(429)}");
Code language: C# (cs)
Note: You have to add a reference to System.Configuration in your project (see section below).
This outputs the following:
We have 3 retry status codes
Retry when status code is 404? False
Retry when status code is 429? True
Code language: plaintext (plaintext)
This example shows how to parse comma-separated integers, but you can apply this approach to any target type.
Add a reference to System.Configuration
To use ConfigurationManager for getting values from app.config, you’ll need to add a reference to System.Configuration:
- Right-click References.
- Click Add Reference.
- In Assemblies > Framework, find System.Configuration and tick the box.
- Click OK.