Daniel Beer Atom | RSS | About

C# INI-file parser

3 Jun 2019

INI-like formats are understandably popular as human-readable configuration files for many server applications. Presented here is a very small (under 300 lines) parser written in C#, supporting a flexible variant of the format.

The source code is here:

It allows for section names delimited with [ and ], and key-value pairs separated by an = sign, as is common. It also supports quoted value strings, including multi-line values and escape sequences. The following escape sequences are recognized:

\x
8-bit escape sequence: followed by 2 hexadecimal characters.
\u
Unicode hexadecimal escape sequence: followed by 4 hexadecimal characters.
\0
NUL character.
\a
ASCII character 7 (bell).
\b
ASCII character 8 (backspace).
\t
ASCII character 9 (tab).
\r
ASCII character 13 (carriage return).
\n
ASCII character 10 (line-feed).
\
When used at the end of a line, this suppresses the trailing line ending (this works for both MS-DOS and Unix line endings).

Comments, denoted by ; and continuing to the end of the line, may be present anywhere outside a quoted string or section name. Keys without values are valid, and are treated as being present but having a blank value. Keys that appear before any section has been defined are treated as belonging to an implicitly-defined section with a blank name.

Parse errors are identified with a thrown exception, containing a message indicating the cause of the error and the position in the file where it occured.

There are two ways to use the parser. You can use a simple dictionary-like interface if you don't need to deal with repeat instances of keys in a block and you don't care about order:

var cfg = new INI.INIDictionary(fileContents);

// Returns null if the given key is not defined
var myvar = cfg.Get("section-name", "key-name");

// Returns a default value if key is not defined
var myvar2 = cfg.Get("section-name", "key-name", "default");

A lower-level interface allows the enumeration of blocks as they appear in the file. This interface is used in the constructor for INIDictionary.

Licence

Copyright (C) 2017 Daniel Beer <dlbeer@gmail.com>

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.