ASP.NET Core appsettings.json update in code

后端 未结 9 1999
小鲜肉
小鲜肉 2020-12-13 01:54

I am currently working on project using asp.net core v1.1, and in my appsettings.json I have:

\"AppSettings\": {
   \"AzureConnectionKey\": \"***\",
   \"Azu         


        
9条回答
  •  温柔的废话
    2020-12-13 02:22

    I took Qamar Zamans code (thank you) and modified it to allow for editing parameters which are more:than:one:layer:deep.

    Hope it helps someone out, surprised that this isn't a library feature somewhere.

    public static class SettingsHelpers
    {
        public static void AddOrUpdateAppSetting(string sectionPathKey, T value)
        {
            try
            {
                var filePath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
                string json = File.ReadAllText(filePath);
                dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
    
                SetValueRecursively(sectionPathKey, jsonObj, value);
    
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(filePath, output);
    
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error writing app settings | {0}", ex.Message);
            }
        }
    
        private static void SetValueRecursively(string sectionPathKey, dynamic jsonObj, T value)
        {
            // split the string at the first ':' character
            var remainingSections = sectionPathKey.Split(":", 2);
    
            var currentSection = remainingSections[0];
            if (remainingSections.Length > 1)
            {
                // continue with the procress, moving down the tree
                var nextSection = remainingSections[1];
                SetValueRecursively(nextSection, jsonObj[currentSection], value);
            }
            else
            {
                // we've got to the end of the tree, set the value
                jsonObj[currentSection] = value; 
            }
        }
    

提交回复
热议问题