https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_1.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-frontend-js-gcm.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_2.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_3.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-build-related-posts-related-posts.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_4.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-frontend-js-wca.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-jquery-jquery.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-jquery-jquery-migrate.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_5.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_6.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_7.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_8.js?ver=1765154690
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • Advanced Python Topics
    • AWS Learning Roadmap
    • JWT Complete Guide
    • Git CheatSheet
  • Explore
    • Programming
    • Development
      • microservices
      • Front End
    • Database
    • DevOps
    • Productivity
    • Tutorial Series
      • C# LinQ Tutorials
      • PHP Tutorials
  • Dev Tools
    • JSON Formatter
    • Diff Checker
    • JWT Decoder
    • JWT Generator
    • Base64 Converter
    • Data Format Converter
    • QR Code Generator
    • Javascript Minifier
    • CSS Minifier
    • Text Analyzer
  • About
  • Contact
CodeSamplez.com

CodeSamplez.com

Programming And Development Resources

You are here: Home / Development / App Config File in C#: Simplify Your Application Settings

App Config File in C#: Simplify Your Application Settings

Updated April 30, 2025 by Rana Ahsan 11 Comments ⏰ 7 minutes

App Config File in C# Application

Ever felt the pain of recompiling your entire C# application just to change a simple database connection string? I’ve been there, and it’s incredibly frustrating. As a seasoned developer, I can tell you that properly leveraging app config file in C# is absolutely essential for building flexible, maintainable applications. In this comprehensive guide, I’ll show you exactly how to master configuration management in your C# projects.

Why You Should NEVER Hardcode Configuration Values

Let’s get real – hardcoding configuration values in your C# applications is a complete disaster waiting to happen. Here’s why:

  • Deployment nightmares – Each environment change requires recompilation
  • Customer customization headaches – Different clients need different settings
  • Maintenance hell – New developers waste hours searching through code
  • Security risks – Sensitive credentials embedded in your codebase

The solution? C#’s built-in configuration system lets you externalize all these settings into XML-based config files. Your application reads these values at runtime, eliminating the need for constant recompilation.

Understanding app config file in C#: App.config vs Web.config

Before diving into implementation, let’s clarify which config file you should use:

  • App.config – For desktop applications (WinForms, WPF, Console apps)
  • Web.config – For web applications (ASP.NET, MVC, Web API)

Both files use identical XML formatting and are automatically processed by the .NET runtime. Throughout this guide, I’ll use “config file” to refer to either one.

Simple Configuration Settings: The AppSettings Approach

Let’s start with the most common scenario – storing simple key-value pairs. This approach is perfect for straightforward configuration needs.

Step 1: Add Settings to Your Config File

Open your app.config or web.config file and add the following within the <configuration> node:

<appSettings>
    <add key="DatabaseServer" value="localhost"/>
    <add key="ApiEndpoint" value="https://api.example.com/v2"/>
    <add key="LoggingEnabled" value="true"/>
    <add key="MaxRetryAttempts" value="3"/>
</appSettings>Code language: HTML, XML (xml)

Step 2: Access Settings in Your C# Code

Retrieving these values couldn’t be easier. First, add the necessary namespace:

using System.Configuration;Code language: CSS (css)

Then access your settings anywhere in your code:

// Reading string values
string dbServer = ConfigurationManager.AppSettings["DatabaseServer"];
string apiUrl = ConfigurationManager.AppSettings["ApiEndpoint"];

// Converting to other types
bool loggingEnabled = bool.Parse(ConfigurationManager.AppSettings["LoggingEnabled"]);
int maxRetries = int.Parse(ConfigurationManager.AppSettings["MaxRetryAttempts"]);Code language: JavaScript (javascript)

For web applications, you might need to use WebConfigurationManager instead:

// Add this namespace
using System.Web.Configuration;

// Then access settings
string dbServer = WebConfigurationManager.AppSettings["DatabaseServer"];Code language: JavaScript (javascript)

Advanced Configuration: Custom Configuration Sections

While AppSettings works great for basic needs, complex applications often require structured configuration with multiple related settings. This is where custom configuration sections shine.

Step 1: Define Your Configuration Section Class

Create a class that extends ConfigurationSection and define properties for each setting:

using System.Configuration;

namespace MyApp.Configuration
{
    public class DatabaseSettings : ConfigurationSection
    {
        [ConfigurationProperty("connectionString", IsRequired = true)]
        public string ConnectionString
        {
            get { return (string)this["connectionString"]; }
        }

        [ConfigurationProperty("timeout", DefaultValue = 30)]
        public int Timeout
        {
            get { return (int)this["timeout"]; }
        }

        [ConfigurationProperty("retryEnabled", DefaultValue = true)]
        public bool RetryEnabled
        {
            get { return (bool)this["retryEnabled"]; }
        }
    }
}

Step 2: Register Your Configuration Section

Next, update your config file to register your custom section:

<configuration>
  <configSections>
    <section name="databaseSettings" type="MyApp.Configuration.DatabaseSettings, MyAssembly"/>
  </configSections>
  
  <databaseSettings 
    connectionString="Server=myServerAddress;Database=myDatabase;User Id=myUsername;Password=myPassword;" 
    timeout="60" 
    retryEnabled="true" />
  
  <!-- Rest of your configuration -->
</configuration>Code language: HTML, XML (xml)

Make sure the type attribute includes both the fully qualified class name and assembly name.

Step 3: Access Your Custom Configuration

Now you can access your configuration with strongly-typed properties:

DatabaseSettings dbSettings = 
    ConfigurationManager.GetSection("databaseSettings") as DatabaseSettings;

if (dbSettings != null)
{
    string connectionString = dbSettings.ConnectionString;
    int timeout = dbSettings.Timeout;
    
    // Use the configuration values
    SqlConnection connection = new SqlConnection(connectionString);
    connection.ConnectionTimeout = timeout;
    <em>// ...</em>
}Code language: JavaScript (javascript)

Creating Collection-Based Configuration Sections

Sometimes you need to configure collections of items. The .NET Framework has you covered with the ConfigurationElementCollection class.

Step 1: Define Your Collection Item Element

First, create a class for each item in your collection:

public class EndpointElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
    public string Name
    {
        get { return (string)this["name"]; }
    }

    [ConfigurationProperty("url", IsRequired = true)]
    public string Url
    {
        get { return (string)this["url"]; }
    }
    
    [ConfigurationProperty("timeout", DefaultValue = 30)]
    public int Timeout
    {
        get { return (int)this["timeout"]; }
    }
}

Step 2: Create the Collection Class

Next, create a collection class:

public class EndpointCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new EndpointElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((EndpointElement)element).Name;
    }
    
    public EndpointElement this[int index]
    {
        get { return (EndpointElement)BaseGet(index); }
    }
    
    public new EndpointElement this[string name]
    {
        get { return (EndpointElement)BaseGet(name); }
    }
}

Step 3: Create the Section Class

Create your section class that includes the collection:

public class ApiSettings : ConfigurationSection
{
    [ConfigurationProperty("endpoints")]
    public EndpointCollection Endpoints
    {
        get { return (EndpointCollection)this["endpoints"]; }
    }
}

Step 4: Configure in Your Config File

Update your config file:

<configuration>
  <configSections>
    <section name="apiSettings" type="MyApp.Configuration.ApiSettings, MyAssembly"/>
  </configSections>
  
  <apiSettings>
    <endpoints>
      <add name="Primary" url="https://api.example.com/v1" timeout="30" />
      <add name="Backup" url="https://backup.example.com/v1" timeout="60" />
    </endpoints>
  </apiSettings>
</configuration>Code language: HTML, XML (xml)

Step 5: Access the Collection

Now you can iterate through your collection:

ApiSettings apiSettings = ConfigurationManager.GetSection("apiSettings") as ApiSettings;

foreach (EndpointElement endpoint in apiSettings.Endpoints)
{
    Console.WriteLine($"Name: {endpoint.Name}, URL: {endpoint.Url}, Timeout: {endpoint.Timeout}");
    // Use the endpoint...
}

// Or access by name
EndpointElement primary = apiSettings.Endpoints["Primary"];Code language: PHP (php)

Connection Strings: A Special Configuration Case

Database connection strings are so common that .NET provides a dedicated section for them.

Step 1: Add Connection Strings to Config

<configuration>
  <connectionStrings>
    <add name="MainDB" 
         connectionString="Server=myServerAddress;Database=myDatabase;User Id=myUsername;Password=myPassword;" 
         providerName="System.Data.SqlClient" />
    <add name="LogDB" 
         connectionString="Server=logServer;Database=logs;User Id=logger;Password=logPwd;" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>Code language: HTML, XML (xml)

Step 2: Access Connection Strings

Retrieve connection strings with:

string mainDbConnection = ConfigurationManager.ConnectionStrings["MainDB"].ConnectionString;
string providerName = ConfigurationManager.ConnectionStrings["MainDB"].ProviderName;

// Use with your database connection
using (SqlConnection connection = new SqlConnection(mainDbConnection))
{
    // Work with your database
}Code language: JavaScript (javascript)

Modifying Configuration at Runtime

While config files are typically read-only during runtime, there are situations where you need to update settings programmatically.

// Update AppSettings
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["LoggingEnabled"].Value = "false";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");Code language: JavaScript (javascript)

Be careful with this approach as it modifies the physical config file and affects all instances of your application.

Best Practices for App Config Files in C#

After years of working with C# configuration, here are my hard-won best practices:

  1. Never store sensitive information in plain text – Use encryption for passwords and API keys
  2. Keep configuration focused – Don’t turn your config file into a data store
  3. Use strongly-typed settings classes – Minimize string-based lookups
  4. Add validation – Validate config values at startup, not when they’re first used
  5. Implement default values – Make your app resilient to missing configuration
  6. Use configuration transforms – Different settings for development, staging, and production
  7. Document your settings – Add comments in the config file describing each setting

Configuration in Modern .NET Applications

While the XML-based configuration system has served .NET developers well for decades, newer .NET applications (especially .NET Core and .NET 5+) have moved to a more flexible JSON-based configuration system.

If you’re building a new application, consider using the modern configuration approach with Microsoft.Extensions.Configuration. However, understanding the traditional configuration system remains valuable, especially when maintaining existing applications.

Also consider exploring official Microsoft document for further references

Conclusion

App config file in C# is a powerful tool for making your applications more flexible and maintainable. By externalizing configuration values, you eliminate the need for recompilation when settings change, making deployment and customization significantly easier.

Whether you’re building a simple console application or a complex enterprise system, proper configuration management is essential. The techniques covered in this guide will help you implement robust configuration handling in your C# applications.

Remember, the time you invest in setting up proper configuration pays off tremendously throughout the development and maintenance lifecycle of your application. Happy coding!

Share if liked!

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to share on Tumblr (Opens in new window) Tumblr
  • Click to share on Pocket (Opens in new window) Pocket

You may also like


Discover more from CodeSamplez.com

Subscribe to get the latest posts sent to your email.

First Published On: December 18, 2010 Filed Under: Development Tagged With: .net, c#

About Rana Ahsan

Rana Ahsan is a seasoned software engineer and technology leader specialized in distributed systems and software architecture. With a Master’s in Software Engineering from Concordia University, his experience spans leading scalable architecture at Coursera and TopHat, contributing to open-source projects. This blog, CodeSamplez.com, showcases his passion for sharing practical insights on programming and distributed systems concepts and help educate others.
Github | X | LinkedIn

Reader Interactions

Comments

  1. tushar rana says

    February 9, 2012 at 10:43 AM

    thanx RANA.,JAY RANA.

    Reply
  2. M.S.Patil says

    July 27, 2012 at 10:07 AM

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Data.SqlClient;

    public partial class datagrid : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
    //SqlConnection conn = new SqlConnection(“data source=localhost\\sqlexpress;Initial Catalog=patil;Integrated Security=SSPI”);
    string con = ConfigurationManager.ConnectionStrings[“patil”].ConnectionString;
    SqlConnection conn = new SqlConnection(con);
    string sqlsrting = “spr_displaydata”;
    SqlCommand cmd = new SqlCommand(sqlsrting, conn);
    SqlDataAdapter Dataadpt = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    Dataadpt.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();

    }

    }

    WEB.CONFIG File:

    Reply
  3. M.S.Patil says

    July 27, 2012 at 10:09 AM

    what about windows development?

    Reply
  4. fam says

    December 4, 2014 at 4:26 PM

    In order to get this working I had to add the namespace in the ConfigSections of the config file:

    Reply
    • Shaji George says

      July 29, 2015 at 10:59 AM

      Could you please show the sample config file after you added the namespace in the ConfigSections?

      Reply
  5. charitha says

    May 4, 2015 at 8:01 AM

    I am using a .bat file in c# code. i have hard coded that path in code. i want to give the path in .config in order to run it in IIS server. Could you please help me?

    Reply
  6. Shaji George says

    July 29, 2015 at 11:00 AM

    When I try your sample
    var settings = ConfigurationManager.GetSection(“mySettings”);
    MySettings current;
    if (settings != null)
    {
    current = settings as MySettings;
    string valueToUse = current.ApiKey;
    //use the value
    }

    the ‘seetings’ variable is always null. How do I fix it?

    Reply
    • paul says

      April 4, 2016 at 7:19 AM

      no pblim

      Reply
  7. paul says

    April 2, 2016 at 12:35 AM

    hi, can u use in this php

    Reply
    • Bob says

      April 8, 2016 at 1:57 PM

      Yes Paul, you can use this in PHP. Just copy and paste the code into the code file, it should work perfect for you.

      Reply
  8. Neha says

    February 12, 2024 at 7:14 AM

    Hi…Can we save app.config by different extension like app.xml and use ConfigurationManager to access it

    Reply

Leave a ReplyCancel reply

Primary Sidebar

  • Facebook
  • X
  • Pinterest
  • Tumblr

Subscribe via Email

Top Picks

python local environment setup

Python Local Development Environment: Complete Setup Guide

In-Depth JWT Tutorial Guide For Beginners

JSON Web Tokens (JWT): A Complete In-Depth Beginners Tutorial

The Ultimate Git Commands CheatSheet

Git Commands Cheatsheet: The Ultimate Git Reference

web development architecture case studies

Web Development Architecture Case Studies: Lessons From Titans

static website deployment s3 cloudfront

Host Static Website With AWS S3 And CloudFront – Step By Step

Featured Dev Tools

  • JSON Formatter
  • Diff Checker

Recently Published

python runtime environment

Python Runtime Environment: Understanding Code Execution Flow

automation with python

Automation With Python: A Complete Guide

python file handling

Python File Handling: A Beginner’s Complete Guide

service worker best practices

Service Worker Best Practices: Security & Debugging Guide

advanced service worker features

Advanced Service Worker Features: Push Beyond the Basics

Footer

Subscribe via Email

Follow Us

  • Facebook
  • X
  • Pinterest
  • Tumblr

Demos

  • Demo.CodeSamplez.com

Explore By Topics

Python | AWS | PHP | C# | Javascript

Copyright © 2025

https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_9.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_10.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-dist-hooks.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-dist-i18n.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_11.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-jetpack-assets-build-i18n-loader.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_12.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-dist-vendor-wp-polyfill.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-dist-url.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_13.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-build-instant-search-jp-search.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-wp-includes-js-comment-reply.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-wp-includes-js-hoverIntent.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-menu-superfish.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-menu-superfish.args.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-lib-js-skip-links.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_14.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-magazine-pro-js-responsive-menus.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_15.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-jetpack-modules-wpgroho.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-assets-js-googlesitekit-consent-mode-bc2e26cfa69fcd4a8261.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_16.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-public-js-sassy-social-share-public.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-assets-js-googlesitekit-events-provider-wpforms-ed443a3a3d45126a22ce.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_17.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_18.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-assets-js-wp-consent-api.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_19.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-js-dist-dom-ready.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-blocks-subscriptions-view.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_20.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-build-sharedaddy-sharing.min.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_21.js?ver=1765154690
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_development-application-settings-c-sharp-1-187-inline_script_22.js?ver=1765154690