How to Parse a Comma-Separated String from App.config in C#
By FoxLearn 1/22/2025 9:22:17 AM 147
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.
For example: 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.
For example, how to parse the retryStatusCodes
setting and store the values in a HashSet<int>
:
using System.Configuration; using System.Linq; // c# configurationmanager 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.
C# ConfigurationManager
In C#, ConfigurationManager
is a class in the System.Configuration
namespace used to access configuration files, such as app.config
or web.config
. It enables you to retrieve application settings, connection strings, and other configuration information.
Accessing AppSettings: The appSettings
section in your configuration file contains key-value pairs.
string retryStatusCodes = ConfigurationManager.AppSettings["retryStatusCodes"];
Accessing Connection Strings: The connectionStrings
section is commonly used to store database connection details.
<configuration> <connectionStrings> <add name="DefaultConnection" connectionString="Server=.;Database=MyDB;Trusted_Connection=True;" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
For example:
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
For modern .NET Core/5/6+, use the IConfiguration
interface from Microsoft.Extensions.Configuration
.
For example: appsettings.json
:
{ "AppSettings": { "AppName": "MyApplication", "Version": "1.0.0" }, "ConnectionStrings": { "DefaultConnection": "Server=.;Database=MyDB;Trusted_Connection=True;" } }
Usage:
using Microsoft.Extensions.Configuration; class Program { static void Main() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); string appName = config["AppSettings:AppName"]; string version = config["AppSettings:Version"]; string connectionString = config.GetConnectionString("DefaultConnection"); } }
- How to fix 'Failure sending mail' in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
- How to start, stop and verify if a service exists in C#