Reputation: 1
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
Reputation: 186668
You don't want Stream
s 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
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
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:
await
.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