Home > Back-end >  Creating a txt from listbox but without the last blank line
Creating a txt from listbox but without the last blank line

Time:04-30

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!

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

    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]);
                }
            }
        }
    }
  •  Tags:  
  • c#
  • Related