Click here to Skip to main content
15,889,096 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hey guys,

i have got a list called 'tokens' and i want to be able to save and load them. i want to be able to do something like:

VB
if a.startswith("save ")
dim sw as streamwriter = new streamwriter(appdomain.currentdomain.basedirectory & a.substring(5) & ".txt")
sw.write(tokens)
sw.close()


i want to be able to do something like that, but it doesn't work. can you please help me?
Posted

First of all, its not nice to ask about your problem with some object tokens without showing the definition of its type. It's also not nice to show the code which does not compile. What, was the using a fragment of real code a problem? How about copy/paste?

However, it does not matter it you try to use the "solution" like in the code you show. Let's understand why it cannot work. Essentially,
C#
sw.Write(tokens);

will output
C#
sw.Write(tokens.ToString());


For lists, other containers and most other types it will simply output the string containing the type name; so, what's the use?

You need to use some kind of serialization, and this is something you will probably need to learn. Please start here:
http://en.wikipedia.org/wiki/Serialization[^],
http://msdn.microsoft.com/en-us/library/ms233843.aspx[^],
http://msdn.microsoft.com/en-us/library/system.runtime.serialization%28v=vs.100%29.aspx[^].

I would strongly recommend to use Data Contract and DataContractSerializer. Please see:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^],
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx[^].

This approach is easiest to use, very robust, universal and non-intrusive. I advocate this approach in my past answers:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^].

—SA
 
Share this answer
 
As you can see here[^], Write has a number of overloads but none of them can take a list or collection as input.
Loop through your list and write text line by line.
 
Share this answer
 
v2
Comments
Member 8378691 10-Jun-12 23:38pm    
what about loading text into the list? i need to save and load text into the list. and could you please give me some code to work with?
Abhinav S 10-Jun-12 23:42pm    
http://www.dotnetperls.com/streamwriter is a good sample that could help you. Look at the loop section, that is basically what you need to do - you can load data into a list.

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