1

I am working on a program where users can upload a textfile with list of links, and after the upload is successful, the lines of the textfile is divided in two listbox where listbox1 contains 50% of the lines in textfile and listbox2 contains remaining 50% .

private void readFile()
    {
        int linenum = 1;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "Text Files|*.txt";
        openFileDialog1.Title = "Select a Text file";
        openFileDialog1.FileName = "";
        DialogResult result = openFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;

            string[] text = System.IO.File.ReadAllLines(file);

            foreach (string line in text)
            {
                if (linenum <= 150)
                {
                    listBox1.Items.Add(line);
                }
                else
                {
                    listBox2.Items.Add(line);
                }

                linenum++;


            }


        }

This code works fine when i know the exact numbers of line in text file, but it throws exception when the textfile consist less line. I am trying to divide the file in two equal parts and show it in two listbox. any advice or suggestion please.

sauk
  • 55
  • 8

2 Answers2

5

Use the Length-property of the text array. The value of it is equal to the count of members (lines) in the array:

string[] text = System.IO.File.ReadAllLines(file);
int current = 0;

foreach (string line in text)
{
   if (current <= text.Length / 2)
   {
      listBox1.Items.Add(line);
   }
   else
   {
      listBox2.Items.Add(line);
   }

   current++;
}
Matten
  • 17,365
  • 2
  • 42
  • 64
0
        var textfile = new string[]{"1","2","3","4"};
        List<string> listBox1 = new List<string>();
        List<string> listBox2 = new List<string>();
        listBox1.AddRange(textfile.Take(textfile.Length / 2));
        listBox2.AddRange(textfile.Skip(textfile.Length / 2).Take(textfile.Length / 2));
Lineesh
  • 106
  • 1
  • 1
  • 6