Saving lists to txt file
C#ListC# Problem Overview
I'm trying to save a list to a text file.
This is my code:
public void button13_Click(object sender, EventArgs e)
{
TextWriter tw = new StreamWriter("SavedLists.txt");
tw.WriteLine(Lists.verbList);
tw.Close();
}
This is what I get in the text file:
>System.Collections.Generic.List`1[System.String]
Do I have to use ConvertAll<>
? If so, I'm not sure how to use that.
C# Solutions
Solution 1 - C#
Framework 4: no need to use StreamWriter:
System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);
Solution 2 - C#
Assuming your Generic List is of type String:
TextWriter tw = new StreamWriter("SavedList.txt");
foreach (String s in Lists.verbList)
tw.WriteLine(s);
tw.Close();
Alternatively, with the using keyword:
using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
foreach (String s in Lists.verbList)
tw.WriteLine(s);
}
Solution 3 - C#
@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.