Saving lists to txt file

C#List

C# 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJared PriceView Question on Stackoverflow
Solution 1 - C#Eric Bole-FeysotView Answer on Stackoverflow
Solution 2 - C#jgallantView Answer on Stackoverflow
Solution 3 - C#Reacher GiltView Answer on Stackoverflow