-->

Use app.config from fsx file

2019-06-20 05:43发布

问题:

Is it possible to use an app.config file from a F# script (fsx) file? If so, how? Where do I put the file and what will it be called?

回答1:

The linked question by @JoeB provides 2 answers which are more suited to F# Interactive than .fsx scripts. I provide a good solution for F# scripts below:

Given this app.config file:

<configuration>
    <appSettings>
        <add key="foo" value="bar"/>
    </appSettings>
</configuration>

Read foo this way:

let appConfigPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "app.config")
let fileMap = ExeConfigurationFileMap()
fileMap.ExeConfigFilename <- appConfigPath
let config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
let foo = config.AppSettings.Settings.["foo"].Value
Console.WriteLine(foo)