.NET - Access custom sections in app.config

如下所示,我们在配置文件app.config中增加了自定义段 Paths

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!-- configSections 必须是第一个节点 -->
    <configSections>
        <section name="Paths" type="System.Configuration.NameValueSectionHandler"/>
    </configSections>
 
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
 
    <Paths>
        <add key="USER_HOME" value="C:\Home" />
        <add key="BIN_HOME" value="C:\Bin" />
        <add key="REPO_HOME" value="C:\Repos" />
    </Paths>
</configuration>

在程序中访问这些配置项

using System.Collections.Specialized;
using System.Configuration;
 
namespace app_custom_section
{
    class Program
    {
        static void Main(string[] args)
        {
            var section = ConfigurationManager.GetSection("Paths") as NameValueCollection;
            if (section != null) {
                var home = section["USER_HOME"];
                var bin = section["BIN_HOME"];
                var repo = section["REPO_HOME"];
            }
        }
    }
}