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);
}
}
}
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
implementsIDisposable
, it's best to implement it with ausing
statement. And really with anything that implementsIDisposable
, you should either useusing
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 theusing
statement closes, it implicitly callsstreamWriter.Dispose()
, which implicitly callsstreamWriter.Close()
. (For readability, you can leave an explicit call tostreamWriter.Close()
in there if you like.)Here's the recommended way, with
using
: