ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Configuration Files
    Advanced ProgrammingTopic 24 of 55

    Configuration Files

    7 minread
    1,145words
    Intermediatelevel

    Configuration Files in C#

    Configuration files are used in software development to store settings and parameters that an application can read at runtime. This externalizes configuration from the application code, making it more flexible, maintainable, and customizable. In C# and the .NET framework, configuration files are commonly used to manage application settings like database connection strings, logging preferences, environment-specific settings, and more.

    1. Types of Configuration Files in C#

    A. App.config / Web.config (XML-based)

    In .NET Framework applications (e.g., WinForms, WPF, ASP.NET), the configuration files are typically in XML format. The two most common XML-based configuration files are:

    • app.config: Used in desktop and console applications.
    • web.config: Used in web applications like ASP.NET WebForms or MVC.

    These files allow developers to store application-specific settings, such as database connections, logging configurations, application behavior, and more.

    Example of app.config:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <!-- App settings -->
      <appSettings>
        <add key="AppTitle" value="My C# Application" />
        <add key="MaxUsers" value="100" />
      </appSettings>
    
      <!-- Connection strings -->
      <connectionStrings>
        <add name="DatabaseConnection" 
             connectionString="Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;" 
             providerName="System.Data.SqlClient" />
      </connectionStrings>
    
      <!-- Other configuration sections -->
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
      </system.web>
    </configuration>
    
    • appSettings: Stores simple key-value pairs for application settings.
    • connectionStrings: Stores connection strings for databases.
    • system.web: Contains web-specific settings like compilation, authentication, etc.

    These settings can be read at runtime using the ConfigurationManager class in C#:

    using System.Configuration;
    
    string appTitle = ConfigurationManager.AppSettings["AppTitle"];
    string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
    

    B. appsettings.json (JSON-based)

    With the introduction of .NET Core and the modern .NET 5+ framework, JSON became the preferred format for configuration files. The appsettings.json file is used in ASP.NET Core and other modern .NET applications to store settings in a hierarchical and human-readable format.

    Example of appsettings.json:
    {
      "AppSettings": {
        "AppTitle": "My C# Application",
        "MaxUsers": 100
      },
      "ConnectionStrings": {
        "DatabaseConnection": "Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }
    

    In .NET Core, you can access these configuration settings via the IConfiguration interface, which supports a flexible system for accessing hierarchical configuration data.

    using Microsoft.Extensions.Configuration;
    
    public class MyService
    {
        private readonly IConfiguration _configuration;
    
        public MyService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void PrintAppTitle()
        {
            string appTitle = _configuration["AppSettings:AppTitle"];
            Console.WriteLine(appTitle);
        }
    }
    

    C. Environment-Specific Configuration Files

    Both .NET Framework and .NET Core support the use of environment-specific configuration files. This allows for different configuration settings based on the environment (e.g., Development, Production, Staging).

    In .NET Core, you can use files such as:

    • appsettings.Development.json
    • appsettings.Production.json
    • appsettings.Staging.json

    These files override the settings in the appsettings.json file based on the environment the application is running in.

    For example, appsettings.Development.json might contain:

    {
      "ConnectionStrings": {
        "DatabaseConnection": "Server=devServer;Database=devDB;"
      }
    }
    

    And appsettings.Production.json might contain:

    {
      "ConnectionStrings": {
        "DatabaseConnection": "Server=prodServer;Database=prodDB;"
      }
    }
    

    You can specify the environment by setting the ASPNETCORE_ENVIRONMENT environment variable, which determines which configuration file will be used:

    set ASPNETCORE_ENVIRONMENT=Production
    

    .NET Core will then automatically load the appropriate configuration file for that environment.

    D. User Secrets (for Development)

    In development environments, user secrets can be used to store sensitive data such as API keys, passwords, or connection strings without hardcoding them into the configuration files.

    User secrets are stored in a separate file on the local machine and are not checked into source control. You can manage user secrets via the .NET CLI:

    dotnet user-secrets set "ConnectionStrings:DatabaseConnection" "Server=localhost;Database=myDB;User Id=myUser;Password=myPassword;"
    

    These secrets are automatically loaded into the application's configuration when the environment is set to Development.

    E. Command-Line Arguments and Environment Variables

    In addition to configuration files, .NET Core and .NET 5+ support loading configuration values from command-line arguments and environment variables, which can be particularly useful for containerized applications (e.g., Docker).

    For example, you can pass configuration settings to an application using command-line arguments:

    dotnet run --AppSettings:AppTitle "My Application"
    

    Alternatively, environment variables can be used for configuration:

    set ConnectionStrings__DatabaseConnection="Server=prodServer;Database=prodDB;"
    

    These values will be automatically incorporated into the application's configuration system.


    2. How to Access Configuration Data

    A. Accessing Configuration in .NET Framework

    In .NET Framework, configuration data from the app.config or web.config is accessed via the ConfigurationManager class:

    using System.Configuration;
    
    string appTitle = ConfigurationManager.AppSettings["AppTitle"];
    string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
    
    • AppSettings are accessed using ConfigurationManager.AppSettings.
    • ConnectionStrings are accessed via ConfigurationManager.ConnectionStrings.

    B. Accessing Configuration in .NET Core

    In .NET Core (and .NET 5+), configuration is typically injected into classes using Dependency Injection. The IConfiguration interface is used to retrieve configuration values from various sources (e.g., appsettings.json, environment variables, command-line arguments).

    Example of accessing configuration in .NET Core:

    using Microsoft.Extensions.Configuration;
    
    public class MyService
    {
        private readonly IConfiguration _configuration;
    
        public MyService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void PrintAppTitle()
        {
            string appTitle = _configuration["AppSettings:AppTitle"];
            Console.WriteLine(appTitle);
        }
    }
    

    In the above example, the IConfiguration instance is injected into the MyService constructor. Configuration values can be accessed through the IConfiguration object using a key path (e.g., AppSettings:AppTitle).


    3. Common Configuration Sections

    Configuration files often contain standard sections such as:

    • appSettings: Stores simple key-value pairs for application-specific settings.
    • connectionStrings: Stores connection strings for databases or services.
    • Logging: Configures logging levels and logging destinations.
    • system.web (for web applications): Configures settings like authentication, session state, etc.

    Example of the Logging section in appsettings.json:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }
    

    In this example, the LogLevel section specifies the logging levels for different namespaces.


    4. Best Practices for Configuration Management

    • Use Environment-Specific Files: Always use environment-specific configuration files (appsettings.Development.json, appsettings.Production.json) to avoid hardcoding settings for specific environments.

    • Keep Secrets Secure: Store sensitive information like API keys and passwords in environment variables or user secrets (in development). Do not store them in configuration files.

    • Use Default Values: Provide sensible default values in your configuration files to ensure the application works even if certain settings are missing.

    • Leverage Strong Typing: Bind configuration settings to strongly-typed classes whenever possible, as this improves maintainability and error-checking.

    public class AppSettings
    {
        public string AppTitle { get; set; }
        public int MaxUsers { get; set; }
    }
    

    Then bind the configuration like this:

    IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    var appSettings = configuration.GetSection("AppSettings").Get<AppSettings>();
    Console.WriteLine(appSettings.AppTitle);
    

    5. Summary

    Configuration files in C# are a crucial part of managing application settings. They provide a way to externalize configuration from the application code, allowing for easier maintenance and flexibility. The primary configuration file formats in .

    Previous topic 23
    Configuration Overview
    Next topic 25
    Programmatic Access to Configuration

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,145
      Code examples0
      DifficultyIntermediate