ConfigurationManager.AppSettings - How to modify and save?

后端 未结 9 1508
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 05:10

It might sound too trival to ask and I do the same thing as suggested in articles, yet it doesn\'t work as expected. Hope someone can point me to the right direction.

<
相关标签:
9条回答
  • 2020-11-28 06:09

    Remember that ConfigurationManager uses only one app.config - one that is in startup project.

    If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

    So for example unit test project should have their own app.config.

    0 讨论(0)
  • 2020-11-28 06:10

    You can change it manually:

    private void UpdateConfigFile(string appConfigPath, string key, string value)
    {
         var appConfigContent = File.ReadAllText(appConfigPath);
         var searchedString = $"<add key=\"{key}\" value=\"";
         var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
         var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
         var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
         File.WriteAllText(appConfigPath, newContent);
    }
    
    0 讨论(0)
  • 2020-11-28 06:15

    Try adding this after your save call.

    ConfigurationManager.RefreshSection( "appSettings" );
    
    0 讨论(0)
提交回复
热议问题