How to Parse a Comma-Separated String from App.config in C#
By FoxLearn 12/20/2024 1:35:30 AM 17
This is a useful technique when you want to manage multiple configuration values, such as error codes or status codes, and quickly check for their presence in your application.
Let's start with a simple setting in your app.config
. We'll define a key called retryStatusCodes
that holds a comma-separated list of HTTP status codes.
Here's what it looks like in your 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="301,302,403"/> </appSettings> </configuration>
In this example, the retryStatusCodes
setting contains three HTTP status codes (301
, 302
, and 503
), separated by commas.
To retrieve and parse this setting in C#, follow these steps:
First, Use ConfigurationManager.AppSettings
to retrieve the value from app.config
.
Next, Use Split(',')
to break the comma-separated string into individual values, then loop through the split strings and parse them into integers using Int32.Parse()
.
Finally, Use a HashSet<int>
to store the parsed integers. This provides fast lookups, which is especially useful when working with larger sets of values.
Here's the code that demonstrates how to parse the retryStatusCodes
setting and store the values in a HashSet<int>
:
using System.Configuration; using System.Linq; var settings = ConfigurationManager.AppSettings["retryStatusCodes"]; // Retrieve the value from app.config // Split the CSV string, parse each value as an integer, and create a HashSet for efficient lookup var errorCodes = settings.Split(',').Select(i => Int32.Parse(i)); var retryStatusCodes = new HashSet<int>(errorCodes); // Output the result Console.WriteLine($"Total status codes: {retryStatusCodes.Count}"); Console.WriteLine($"Status code is 301? {retryStatusCodes.Contains(301)}"); Console.WriteLine($"Status code is 302? {retryStatusCodes.Contains(302)}");
Output:
Total status codes: 3 Status code is 301? False Status code is 302? True
In order to use ConfigurationManager.AppSettings
to access values from app.config
, you need to add a reference to System.Configuration
in your project.
You can do that by right-clicking on References in the Solution Explorer, then click Add Reference.
In the Assemblies section, locate System.Configuration
, and check the box next to it, then click OK.
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
- Dictionary with multiple values per key in C#