C#
.NET
AppSettings
configuration
app.config

AppSettings get value from .config file

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Reading AppSettings from a .config file is straightforward in .NET, but production bugs appear when keys are missing, values are malformed, or environment overrides are unclear. The safest approach is to centralize configuration reads, validate early, and fail fast for required settings. This keeps runtime behavior predictable across development and deployment.

Basic Read from app.config or web.config

For .NET Framework apps, ConfigurationManager.AppSettings is the standard API.

csharp
1using System;
2using System.Configuration;
3
4class Program
5{
6    static void Main()
7    {
8        string apiUrl = ConfigurationManager.AppSettings["ApiUrl"];
9        Console.WriteLine(apiUrl);
10    }
11}

Example config file:

xml
1<?xml version="1.0" encoding="utf-8" ?>
2<configuration>
3  <appSettings>
4    <add key="ApiUrl" value="https://api.example.com" />
5    <add key="TimeoutSeconds" value="30" />
6  </appSettings>
7</configuration>

This works for classic console, desktop, and ASP.NET Framework applications.

Parse and Validate Typed Values

AppSettings returns strings. Parse once near startup and validate required keys.

csharp
1using System;
2using System.Configuration;
3
4public static class Settings
5{
6    public static string ApiUrl =>
7        ConfigurationManager.AppSettings["ApiUrl"]
8        ?? throw new InvalidOperationException("ApiUrl is missing");
9
10    public static int TimeoutSeconds
11    {
12        get
13        {
14            string raw = ConfigurationManager.AppSettings["TimeoutSeconds"]
15                ?? throw new InvalidOperationException("TimeoutSeconds is missing");
16
17            if (!int.TryParse(raw, out int value))
18                throw new InvalidOperationException("TimeoutSeconds is not a valid integer");
19
20            return value;
21        }
22    }
23}

This avoids scattered string parsing and inconsistent defaults.

Centralize Access in One Configuration Service

Instead of reading keys everywhere, create a small typed configuration class.

csharp
1public sealed class AppConfig
2{
3    public string ApiUrl { get; }
4    public int TimeoutSeconds { get; }
5
6    public AppConfig()
7    {
8        ApiUrl = Settings.ApiUrl;
9        TimeoutSeconds = Settings.TimeoutSeconds;
10    }
11}

Centralization improves testability and makes key ownership obvious.

Environment-Specific Config Files

In classic .NET deployments, transforms can provide environment-specific values. Keep key names consistent and only vary values.

Practical guidance:

  • store non-secret environment values in config transforms.
  • keep secrets out of source-controlled .config files.
  • use secure secret stores or deployment-time injection for credentials.

This pattern reduces accidental secret leaks.

Handling Missing or Optional Keys

Not all keys must be mandatory. For optional keys, define explicit defaults in one place.

csharp
1public static bool FeatureXEnabled
2{
3    get
4    {
5        string raw = ConfigurationManager.AppSettings["FeatureXEnabled"];
6        return bool.TryParse(raw, out bool enabled) && enabled;
7    }
8}

Avoid silent defaults for keys that affect safety, billing, or data integrity.

Debugging Configuration Issues

When values seem wrong:

  1. confirm which config file is loaded at runtime.
  2. log effective non-sensitive settings at startup.
  3. verify transform output in build artifacts.

Lightweight startup diagnostics can save hours of incident triage.

csharp
Console.WriteLine($"ApiUrl={Settings.ApiUrl}, TimeoutSeconds={Settings.TimeoutSeconds}");

Do not print secrets in logs.

.NET Core Note

If your app uses modern .NET configuration with appsettings.json, use IConfiguration and options binding instead of ConfigurationManager. The title here is about .config files, so choose API by runtime model rather than mixing both in one application.

Unit Testing Configuration Readers

To keep configuration logic testable, isolate parsing from static global calls. You can read raw strings once and pass them into a parser function that unit tests can cover without loading real config files.

csharp
1public static int ParseTimeout(string? raw)
2{
3    if (string.IsNullOrWhiteSpace(raw)) throw new InvalidOperationException("Timeout missing");
4    if (!int.TryParse(raw, out int value)) throw new InvalidOperationException("Timeout invalid");
5    return value;
6}

This prevents hard-to-test static configuration dependencies from spreading through business code.

Common Pitfalls

  • Reading the same keys in many classes with duplicated parsing logic.
  • Assuming all values in AppSettings are valid without validation.
  • Keeping secrets in source-controlled .config files.
  • Relying on implicit defaults for required operational settings.
  • Mixing classic .config APIs and modern options patterns inconsistently.

Summary

  • Use ConfigurationManager.AppSettings for classic .config scenarios.
  • Parse and validate values once at startup.
  • Centralize configuration access in typed helpers.
  • Keep environment overrides explicit and secrets external.
  • Treat configuration as part of application correctness, not only deployment detail.

Course illustration
Course illustration

All Rights Reserved.