Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I would like to save the Tree-view content to a TXT file.
What is the easiest way to save it to txt?

What I have tried:

treeViewIn.Nodes.ToString();

TextWriter tw = new StreamWriter(@"InOrder.txt");
IList list = treeViewIn.Nodes;
     for (int i = 0; i < list.Count; i++)
          {
              string s = (string)list[i];
              tw.WriteLine(s);
          }
     tw.Close();
Posted
Updated 8-Sep-18 23:32pm
Comments
Richard MacCutchan 9-Sep-18 3:34am    
That looks quite easy.

1 solution

There are two problems here: the first is that a treeview is not a "flat" display, it can have branches, and the branches can have twigs:
C#
A
|\
| B
| |\
| | C
| D
|  \
|   E
F
So a simple loop is not a practical way to access all the nodes for storage. It's a recursive data structure, so you need to think about a recursive method to access it all correctly.

The second is a load bigger: a flat data file like a text document is not a good "fit" for recursive data! It's easy to store, but how do you read it back later to reconstruct the original tree based view? And without that ability, you are wasting your time storing the data at all: if you cant read it where is the point?

What I';d suggest is that you look at one of three storage methods: XML data, JSON data, and a relational database. They all have advantages and disadvantages, and which one you should probably chose will depend on how you intend to use the data and what you ne3ed to do with it once you have stored it.

But to be honest, you are probably doing this the wrong way round: designing your data storage based on how you are displaying it is almost certainly a mistake; data is far too important to leave to consider last!
 
Share this answer
 
Comments
Galarist_00 9-Sep-18 4:42am    
I have managed to save to a txt file:

I have added the tree-view content first to a list-box, then I saved from the list-box to a txt file.
OriginalGriff 9-Sep-18 5:43am    
Now regenerate the tree view from just that file...
Graeme_Grant 9-Sep-18 4:53am    
I would do it the same way as you would store a recursive structure in a DB table(s)... I must admit, without knowing the specific structure of the data to be stored, it's hard to give a clear answer...
OriginalGriff 9-Sep-18 5:44am    
It is - but doing it the DB way manually in a text file is a lot of work - I'd go with XML or JSON instead there as it does the "heavy lifting" for you.
Graeme_Grant 9-Sep-18 19:10pm    
Yes, same... Xml, JSON, CSV, etc... there is a lib for that! ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900