I am trying to save the items from a listbox to a file. So I started writing this code:
private void mstri_SaveLog_Click(object sender, EventArgs e)
{
Stream s;
this.sfd_Log.Filter = "Textfiles (*.txt)|*.txt";
DialogResult d = this.sfd_Log.ShowDialog();
if ((d == DialogResult.OK) && (this.lb_Log.Items.Count != 0))
{
for (int i = 0; i < this.lb_Log.Items.Count; i++)
{
if ((s = this.sfd_Log.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(s);
wText.Write(this.lb_Log.Items[i]);
s.Close();
}
}
}
}
There is a new textfile that is created, but it is always empty. But I have no idea where there is a mistake in my code.
Thank you for your help.
I see two problems that are causing the file to be blank. The first problem is that the StreamWriter is buffering up data and is not writing that data to the file. A simple call to wText.Flush() will solve this.
The second problem is that everytime the StreamWriter is closed and reopened, it is starting at the beginning of the file, effectively clearing out whatever you had written to it in the previous iteration. Opening and closing the StreamWriter should occur outside the for-loop.
Here’s how i would do it: