Write a TreeView into a tab-delimited file in C#

[example]

The example Load a TreeView from a tab-delimited file in C# shows how to load a TreeView control from a file. This example shows how to do the converse: write a TreeView control’s values into a file.



The following SaveTreeViewIntoFile method starts the process.

// Write the TreeView's values into a file that uses tabs
// to show indentation.
private void SaveTreeViewIntoFile(string file_name, TreeView trv)
{
    // Build a string containing the TreeView's contents.
    StringBuilder sb = new StringBuilder();
    foreach (TreeNode node in trv.Nodes)
        WriteNodeIntoString(0, node, sb);

    // Write the result into the file.
    File.WriteAllText(file_name, sb.ToString());
}

This method creates a StringBuilder and uses it to build the text that the file will contain. It then loops through the TreeView control’s top-level nodes and calls WriteNodeIntoString (described next) for each.

After it finishes looping through the top-level TreeView nodes, the code writes the StringBuilder object’s contents into the file.

The following code shows the WriteNodeIntoString method.

// Write this node's subtree into the StringBuilder.
private void WriteNodeIntoString(int level, TreeNode node,
    StringBuilder sb)
{
    // Append the correct number of tabs and the node's text.
    sb.AppendLine(new string('\t', level) + node.Text);

    // Recursively add children with one greater level of tabs.
    foreach (TreeNode child in node.Nodes)
        WriteNodeIntoString(level + 1, child, sb);
}

This method recursively writes a node and its subtree into a StringBuidler. The method’s first parameter is the number of tabs that should come before this node’s data. The method starts by appending that number of tabs and the node’s text onto the StringBuilder.

The method then loops through the node’s child nodes. For each child, it calls this method recursively, adding 1 to the number of tabs.

Download the example and the previous example to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, controls, files, recursion and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *