C#C
C#3y ago
fooo1

✅ Reading a yaml file that has multiple types

I'm having trouble finding examples that show how, given a key, to return a value which may be a string, int or list.

---
foo1: some string
foo2:
  - a
  - b
  - 123
foo3: 123


using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Yaml;

public class YamlLib {
  public dynamic ReadYaml(string key) {
    var basePath = AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.IndexOf("bin"));
    var configFileName = Path.Combine(basePath, "appsettings.yml");
    
    var builder = new ConfigurationBuilder();
    builder.AddYamlFile(configFileName);
    var configuration = builder.Build();
    
    // var value = configuration[key];
    // var value = configuration.GetSection(key).GetChildren().Select(x => x.Value).ToList();
    return value;
  }
}


var value = configuration[key]; works on primitive types only;
var value = configuration.GetSection(key).GetChildren().Select(x => x.Value).ToList(); works(ish) on list but not on primitive types.

Whats the path of least complexity to get any value from any key, leaving up to the user to make sure correct methods are used on correct types?
Was this page helpful?