Thursday 12 December 2019

C# - Read AppSettings / Configuration Settings from File

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Reads the app settings kyes information for the provided keys
/// </summary>
/// <param name="filePath"></param>
/// <param name="keysToRead"></param>
/// <returns></returns>
private Dictionary<string, string> ReadAppSettings(string filePath, IEnumerable<string> keysToRead)
{
    JObject appsettingsInfo = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(filePath));
        return appsettingsInfo.Root.Values().
                        Select(item => new { Key = item.Path, Value = item.Value<string>() }).
                        Where(item => keysToRead.Contains(item.Key, StringComparer.InvariantCultureIgnoreCase)).
                        Select(item => new KeyValuePair<string, string>(item.Key, item.Value)).ToDictionary(x => x.Key, x => x.Value);
}

No comments: