1

I use the following method to update appSettings in the config file:

void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Minimal);
    ConfigurationManager.RefreshSection("appSettings");
}

But the saving sometimes breaks long lines (>80 chars).

For example, before saving:

  <appSettings>
    <add key="A very long configuration parameter for example1" value="true" />
    <add key="A very long configuration parameter for example-2" value="true" />
    <add key="A very long configuration parameter for example3" value="Long value" />
  </appSettings>

After saving:

  <appSettings>
    <add key="A very long configuration parameter for example1" value="true" />
    <add key="A very long configuration parameter for example-2"
      value="true" />
    <add key="A very long configuration parameter for example3" value="Long value" />
  </appSettings>

Example #2 exceeds 80 chars and is split into 2 lines.

Example #3 is also >80 chars, but is not split.

Why is it and how to avoid the split?

Edit:

According to the links in the first comments, I understand I can't avoid the split when using ConfigurationManager.

But I'd like to understand the logic/rules - Why my example #3 isn't split although the whole line is longer than example #2 ? Does it depend on the first parameter ("key") only?

Udi Y
  • 258
  • 3
  • 12
  • I'm not sure this built-in behavior can be changed, except by reading and write the file totally by yourself. See here for a somewhat similar question & answers: [Can ConfigurationManager retain XML comments on Save()](https://stackoverflow.com/q/1954358/1220550). Also see this: [C# Configuration Manager- Format string on one line after Save](https://stackoverflow.com/q/43119838/1220550) – Peter B Jun 08 '21 at 14:00
  • Does this answer your question? [C# Configuration Manager- Format string on one line after Save](https://stackoverflow.com/questions/43119838/c-sharp-configuration-manager-format-string-on-one-line-after-save) – Peter B Jun 08 '21 at 14:02
  • @PeterB But what is the logic? Why my example #3 isn't split although longer than example #2 ? – Udi Y Jun 08 '21 at 14:15
  • I'm guessing because the 2nd key is longer than both the other keys. – Peter B Jun 08 '21 at 14:23
  • 1
    It would be interesting to know what *problem* this is causing you. Assuming you're working with properly built tools that understand the semantics of XML, the exact nature of whitespace appearing between two attributes should be *irrelevant*. – Damien_The_Unbeliever Jun 09 '21 at 07:32
  • @Damien_The_Unbeliever By using `ConfigurationSaveMode.Minimal` I expected to have only one line diff comparing to the original file, but got some more. So it makes it more difficult for validation. – Udi Y Jun 09 '21 at 08:16

0 Answers0