How to parse multi line value from config file

536 views Asked by At

I have properties file as follows:. I want to store it in Dictionary(Key-Value pair).

paragraph1~Para1 Line1
           Para1 Line2
           Para1 Line3
paragraph2~Para2 Line1
           Para2 Line2
paragraph3~Para3 Line1
           Para3 Line2
           Para3 Line3

I use following code - but it can only parse 1 line. It does not parse multi line. So for dict["paragraph1"], value is "Para1 Line1"

foreach (var row in File.ReadAllLines("c:\\temp\\properties.txt"))
{
    if (row == String.Empty)
    {
        continue;
    }
    dict.Add(row.Split('~')[0], string.Join("~", row.Split('~').Skip(1).ToArray()));
}
1

There are 1 answers

0
Simon Brown On BEST ANSWER

From what I understand from the question this should work:

        string paragraph = String.Empty;
        foreach (var row in File.ReadAllLines("s.txt").Where(row => row != String.Empty))
        {
            if (!row.Contains('~'))
            {
                dict[paragraph] += " " + row.Trim();
                continue;
            }

            dict.Add(row.Split('~')[0], string.Join("~", row.Split('~').Skip(1).ToArray()));
            paragraph = row.Split('~')[0];
        }

Produces [paragraph1, Para1 Line1 Para1 Line2 Para1 Line3].

Not entirely sure what you're doing with the string.Join, though. This would produce the same output:

            dict.Add(row.Split('~')[0], row.Split('~')[1]);