Alex Rivera | Logout

Best method of Textfile Parsing in C#?

Asked 2008-08-17T22:02:31.097
10

I want to parse a config file sorta thing, like so:

[KEY:Value]     
    [SUBKEY:SubValue]

Now I started with a StreamReader, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me.

One restriction is that it has to work in a Linux/Mono environment (1.2.6 to be exact). I don't have the latest 2.0 release (of Mono), so try to restrict language features to C# 2.0 or C# 1.0.

Edit
Report

2 Answers

0

@Gishu

Actually once I'd accommodated for escaped characters my regex ran slightly slower than my hand written top down recursive parser and that's without the nesting (linking sub-items to their parents) and error reporting the hand written parser had.

The regex was a slightly faster to write (though I do have a bit of experience with hand parsers) but that's without good error reporting. Once you add that it becomes slightly harder and longer to do.

I also find the hand written parser easier to understand the intention of. For instance, here is the a snippet of the code:

private static Node ParseNode(TextReader reader)
{
    Node node = new Node();
    int indentation = ParseWhitespace(reader);
    Expect(reader, '[');
    node.Key = ParseTerminatedString(reader, ':');
    node.Value = ParseTerminatedString(reader, ']');
}
answered 2008-08-18T07:52:29.237
-1

Regardless of the persisted format, using a Regex would be the fastest way of parsing. In ruby it'd probably be a few lines of code.

\[KEY:(.*)\] 
\[SUBKEY:(.*)\]

These two would get you the Value and SubValue in the first group. Check out MSDN on how to match a regex against a string.

This is something everyone should have in their kitty. Pre-Regex days would seem like the Ice Age.

answered 2008-08-18T07:22:11.950

Your Answer