Modify Web.config value at runtime

var config = WebConfigurationManager.OpenWebConfiguration("~");
var section = (AppSettingsSection)config.GetSection("appSettings");
section.Settings["something"].Value = "newValue";
config.Save();

Force IE in Edge Mode

If you’re seeing Internet Exploder loading your site in an old compatibility mode, try adding the following to your web.config file:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="X-UA-Compatible" value="IE=Edge" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

It may or may not work – I haven’t had the time or patience to learn all the various scenarios that screw up Internet Exploder, but this works in at least some scenarios.

Custom config items

app.config/web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="accounts" type="MyApp.Config.AccountsSection, MyApp" />
    </configSections>
    <appSettings></appSettings>
    <accounts host="myhost">
        <add user="abc" password="def" />
        <add user="123" password="456" />
    </accounts>
</configuration>

Config Code

using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace MyApp.Config {
    public class AccountsSection : ConfigurationSection {
        [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
        public AccountCollection Instances {
            get { return (AccountCollection)this[""]; }
            set { this[""] = value; }
        }
        [ConfigurationProperty("host", IsRequired = true)]
        public string Host {
            get { return (string)this["host"]; }
            set { this["host"] = value; }
        }
    }
    public class AccountCollection : ConfigurationElementCollection {
        protected override ConfigurationElement CreateNewElement() {
            return new Account();
        }
        protected override object GetElementKey(ConfigurationElement element) {
            return ((Account)element).User;
        }
    }
    public class Account : ConfigurationElement {
        [ConfigurationProperty("user", IsKey = true, IsRequired = true)]
        public string User {
            get { return (string)base["user"]; }
            set { base["user"] = value; }
        }
        [ConfigurationProperty("password", IsRequired = true)]
        public string Password {
            get { return (string)base["password"]; }
            set { base["password"] = value; }
        }
        public override string ToString() {
            return string.Format("{0} {1}", User, Password);
        }
    }
    public static class AccountConfig {
        private static Dictionary<string, Account> _instances;
        static AccountConfig() {
            _instances = new Dictionary<string, Account>();
            foreach (Account account in ((AccountsSection)ConfigurationManager.GetSection("accounts")).Instances) {
                _instances.Add(account.User, account);
            }
        }
        public static AccountsSection GetSection() {
            return (AccountsSection)ConfigurationManager.GetSection("accounts");
        }
        public static Account GetAccountByUser(string user) {
            return _instances[user];
        }
        public static Account[] GetAll() {
            return _instances.Values.ToArray();
        }
    }
}

In Action

using System;
namespace MyApp {
    class Program {
        static void Main(string[] args) {
            var items = Config.AccountConfig.GetAll();
            foreach (var item in items) {
                Console.WriteLine(item);
            }
            var section = Config.AccountConfig.GetSection();
            Console.WriteLine("host={0}", section.Host);
        }
    }
}

Config for SMTP

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network">
            <network
                host="smtp.something.something"
                defaultCredentials="false"
                enableSsl="true"
                password="1122334455"
                port="587"
                userName="postmaster@example.com"
            />
        </smtp>
    </mailSettings>
</system.net>

Configuration in .NET Core

Here’s some basic examples for reading from a configuration file:

1) Create an appsettings.json file in your project.

2) Add this to your csproj file, so that it gets to your output directory:

<ItemGroup>
    <None Update="appsettings.json">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
</ItemGroup>

3) Install the appropriate NuGet packages:

dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.Binder

4) Add data to your appsettings file, either as simple key-value pairs, or nest them:

{
    "ApplicationName": "Some Application",

    "ConnectionStrings": {
        "CS1": "some-connection-string",
        "CS2": "some-other-connection-string"
    },

    "Queries": {
        "Q1": {
            "ConnectionStringKey": "CS1",
            "QueryText": "some query",
            "Timeout": 40
        },
        "Q2": {
            "ConnectionStringKey": "CS2",
            "QueryText": "some other query"
        }
    }
}

5) Profit:

public class QueryInfo {
    public string ConnectionStringKey { get; set; }
    public string QueryText { get; set; }
}

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();

string appName = config["ApplicationName"];
var queries = config.GetSection("Queries").GetChildren()
    .Select(x => new
    {
        x.Key,
        QueryInfo = x.Get<QueryInfo>()
    }).ToArray();

foreach (var query in queries)
{
    // Special GetConnectionString reads from "ConnectionStrings"
    string connString = config.GetConnectionString(query.QueryInfo.ConnectionStringKey); 
}