SumDum
SumDum

Reputation: 1

How do I save list to text file?

At the moment I have this and it saves (System.Collections.Generic.List'1[System.String]) but I want it to save the text in the string.

private void btnSave_Click(object sender, EventArgs e)
{
    TextWriter tw = new StreamWriter(lblName.Text + ".txt");
    tw.WriteLine(save);
    tw.Close();
}

Upvotes: 0

Views: 1339

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You don't want Streams in simple cases, but File class only:

To save a List<string>:

private void btnSave_Click(object sender, EventArgs e)
{
    File.WriteAllLines($"{lblName.Text}.txt", myListToSave);
}

Or, if you want appending new lines to an existing file:

private void btnSave_Click(object sender, EventArgs e)
{
    File.AppendAllLines($"{lblName.Text}.txt", myListToSave);
}

To save a string:

private void btnSave_Click(object sender, EventArgs e)
{
    File.WriteAllText($"{lblName.Text}.txt", myStringToSave);
}

Upvotes: 2

Ali Hassan
Ali Hassan

Reputation: 966

private void btnSave_Click(object sender, EventArgs e)
{
    TextWriter tw = new StreamWriter(lblName.Text + ".txt");
    foreach (String save in Lists.your_list)
      tw.WriteLine(s);
    tw.Close();
}

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39898

By default, tw.WriteLine(save) calls save.ToString() to convert your object to a string. What you actually want is the content of the List. You could do something like this:

 static async void WriteCharacters()
 {
    using (StreamWriter writer = File.CreateText(lblName.Text + ".txt"))
    {
       foreach(string s in save)
       {
           await writer.WriteLineAsync(s);
       }
    }
}

Couple of details:

  • This method is async. It's a best practice to use async for Input/Output operations. When calling this method, make sure to use await.
  • StreamWriter implements IDisposable which means you can use it in a using { } statement. That way, you can be certain the file always gets closed correctly.

Upvotes: 1

Related Questions