Cover image for Single-file INI editor for .NET that preserves formatting by editing the original text

Pavel Bashkardin

I wrote a single-file INI parser/editor for .NET that preserves formatting using regex instead of dictionaries with JSON support.

I've been experimenting with a different approach to editing INI files in C#.

Most libraries parse the file into dictionaries or objects and then regenerate the entire file when saving. That works well for configuration data, but it usually destroys comments, blank lines, indentation, entry order, or duplicate keys.

Instead, I treat the INI file as plain text and index it with a single regular expression. The parser stores only regex matches and edits the original text directly, so unchanged parts of the file remain byte-for-byte identical.

Some features:

  • Preserves formatting - comments, blank lines and whitespace remain untouched.
  • Duplicate keys - Path=/bin, Path=/usr/binReadStrings() returns both values.
[Paths]
Path=/bin
Path=/usr/bin

Enter fullscreen mode Exit fullscreen mode

  • Global entries - supports key/value pairs before the first section.
  • Configurable comparison - choose Ordinal, InvariantCulture, case-sensitive or insensitive matching.
  • Escape sequences - "Hello\nWorld!" ↔ actual multiline text:

Hello
World!

  • Multiline values
  Script =
  {
  #!/bin/sh
  echo Hello
  echo World
  }

Enter fullscreen mode Exit fullscreen mode

Extracted text:

#!/bin/sh
echo Hello
echo World

  • Embedded JSON
  Config =
  {
    "timeout": 30,
    "retry": 5
  }

Enter fullscreen mode Exit fullscreen mode

Read/write it as a string or as an object.

  • Object mapping
  [Network]
  Port=8080
  Host=localhost

Enter fullscreen mode Exit fullscreen mode

  [IniSection("Network")]
  class NetworkSettings
  {
      public string Host { get; set; }
      [IniEntry("Port")] public int ConnectionPort { get; set; }
      [IniIgnore()] public string Comment { get; set; }
  }

Enter fullscreen mode Exit fullscreen mode

  • Single source file - just add IniFile.cs to project.
  • No external dependencies.

The multiline support was probably the most interesting part. The parser recognizes balanced { ... } blocks using .NET balancing groups, so embedded JSON doesn't get confused with INI section headers.

I'd appreciate any feedback, especially if you spot edge cases I haven't considered.

Source:

Github project
Regex playground