I’m trying to read a text document that is separated into essentially “paragraphs” of info that all have identically formatted headers.
The goal is to add each of the header titles as parents to a treeView and the rest of the header info as children to the treeView.
Adding the headers is easy, however I’m having problems adding the children to the correct parent. I’m using the StreamReader to read each line, find the start of a “paragraph” and create the parent. The children I need to add are going to be on the next three lines. How to I the currentLine from the StreamReader's ReadLine()? Or is there a better way to do this?
using (var sr = new StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
//Sheet name
if (line.Contains("Sheet Name"))
{
string parentNodeName = line.Split('=')[1].Trim();
//Add Parent
treeView.Nodes.Add(parentNodeName);
//Add children, on next 3 lines
treeView.Nodes[parentNodeName].Nodes.Add("Child-1 Text"); //on next line
treeView.Nodes[parentNodeName].Nodes.Add("Child-2 Text"); //on next next line
treeView.Nodes[parentNodeName].Nodes.Add("Child-3 Text"); //etc
}
}
sr.Close();
sr.Dispose();
}
Sample text (“paragraph” header) from file:
800: Sheet Name = Sheet3
999 : Process = 2
1000 : Material = AL,CR,STEEL
1001 : Cut Quality = 0,1,2,3,4,5,6,7,8
Am going to parse these lines to be added to the tree, adding children to identical parent nodes. Like:
Sheet3
2
AL,CR,STEEL
0,1,2,3,4,5,6,7,8
SS
0,1,2,3,4,5,6,7,8
MS
0,1,2,3,4,5
4
AL,CR,STEEL
0,1,2,3,4,5,6,7,8
MS
0,1,2,3,4,5
10
AL,CR,STEEL
0,1,2,3,4,5,6,7,8
SS
0,1,2,3,4,5,6,7,8
Here is sample how you can read file and build TreeView.
Frankly speaking it’s better to split those two operations – parsing file and building tree. But for quick sample will go. Also consider that Dispose() will be called automatically at the end of using block.
Here we parse file. I suppose file is exactly in expected format. No errors handling, no format checking. You free to add some 🙂
And here we add parsed paragraphs to tree.