Single-file INI editor for .NET that preserves formatting by editing the original text
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.
Approach
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.
Features
Preserves formatting - comments, blank lines and whitespace remain untouched.
Duplicate keys -
Path=/bin,Path=/usr/binโReadStrings()returns both values.[Paths] Path = /bin Path = /usr/binGlobal 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 }Extracted text:
#!/bin/sh echo Hello echo WorldEmbedded JSON
Config = { "timeout": 30, "retry": 5 }Read/write it as a string or as an object.
Object mapping
[Network] Port = 8080 Host = localhost[IniSection("Network")] class NetworkSettings { public string Host { get; set; } [IniEntry("Port")] public int ConnectionPort { get; set; } [IniIgnore()] public string Comment { get; set; } }Single source file - just add
IniFile.csto project.No external dependencies.
Multiline Support
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.
Feedback
I'd appreciate any feedback, especially if you spot edge cases I haven't considered.
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.
Comments
No comments yet. Start the discussion.