Write all TreeView nodes to text file

2.8k Views Asked by At

I'm trying to save all TreeNodes with Text="Group" from my TreeView to a file. I'm able to print all TreeNodes with Text="Group" but when I add a StreamWriter plus a file name , the result is a blank file. I am sure there are one or more TreeNodes which name is Group, so that couldn't be the problem. How can I fix my code?

The result for the file can look like this for example

Group 1

Group 0

EDIT:

I found the fix I added streamWriter.Close(); at the end of the CreateSiveFile method, now it works.

Code

    public void CreateSaveFile(string fileName ,TreeView treeView)
    {
        StreamWriter streamWriter = new StreamWriter(fileName);
        // Print each node recursively.
        TreeNodeCollection nodes = treeView.Nodes;
        foreach (TreeNode n in nodes)
        {
            WriteRecursive(streamWriter, n);
        }
    }

    public void WriteRecursive(StreamWriter writer, TreeNode treeNode)
    {
        if (treeNode.Text == "Group")
        {
            writer.WriteLine(String.Format("{0} {1}", treeNode.Text, treeNode.Nodes.Count));
            // Print each node recursively.
            foreach (TreeNode tn in treeNode.Nodes)
            {
                WriteRecursive(writer,tn);
            }
        }
    }
1

There are 1 best solutions below

1
On

Congrats on finding the problem! If you don't mind, I'll point out a useful (and best practice) technique you can use on things like this going forward.

Because StreamWriter implements IDisposable, it's best to implement it with a using statement. And really with anything that implements IDisposable, you should either use using or call .Dispose() explicitly, to let the CLR know to free up its resources. It's not just a best practice, but in this case doing so would've solved the problem of the stream not closing, because when the using statement closes, it implicitly calls streamWriter.Dispose(), which implicitly calls streamWriter.Close(). (For readability, you can leave an explicit call to streamWriter.Close() in there if you like.)

Here's the recommended way, with using:

public void CreateSaveFile(string fileName, TreeView treeView)
{
    using (StreamWriter streamWriter = new StreamWriter(fileName))
    {
        // Print each node recursively.
        TreeNodeCollection nodes = treeView.Nodes;
        foreach (TreeNode n in nodes)
        {
            WriteRecursive(streamWriter, n);
        }
        streamWriter.Close(); // Optional since we have "using", but good practice to include.
    }
}