Creating a txt from listbox but without the last blank line

Viewed 57

thanks for your help! When creating a txt from a listbox, the txt is being generated with a last empty line here is my code:

private void button1_Click(object sender, EventArgs e)
{
    SaveFileDialog lsd = new SaveFileDialog();
    if (lsd.ShowDialog() == DialogResult.OK)
    {
        StreamWriter writer = new StreamWriter(lsd.FileName + ".TXT");
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
      
            writer.WriteLine(listBox1.Items[i]);
        }

        writer.Close();
    }
    lsd.Dispose();
} 

Any Idea on how I can avoid generating that last line?

Thanks again for your help!

3 Answers

how about

  for (int i = 0; i < listBox1.Items.Count; i++)
    {
        if(i == listBox1.Items.Count - 1 && listBox1.Items[i].Length == 0)
            break;
        writer.WriteLine(listBox1.Items[i]);
    }

ie - if its the last line and its blank then ignore it

StreamWriter.WriteLine writes the text representation a span of characters to the string, followed by a line terminator. So, you can avoid generating the last line by using StreamWriter.Write for the last item.

int lastIndex = listBox1.Items.Count - 1;
for (int i = 0; i < lastIndex; i++)
{
    writer.WriteLine(listBox1.Items[i]);
}

writer.Write(listBox1.Items[lastIndex]);

Reference.

    private void button1_Click(object sender, EventArgs e)
    {
        if (listBox1.Items.Count < 1)
            return;

        using (SaveFileDialog lsd = new SaveFileDialog())
        {
            lsd.AddExtension = true;
            lsd.DefaultExt = "txt";
            lsd.Filter = "Text Files|*.txt";

            if (lsd.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter writer = new StreamWriter(lsd.FileName))
                {
                    int i;
                    for (i = 0; i < listBox1.Items.Count - 1; i++)
                    {
                        writer.WriteLine(listBox1.Items[i]);
                    }

                    writer.Write(listBox1.Items[i]);
                }
            }
        }
    }
Related