c # 텍스트 파일의 줄을 두 개의 동일한 부분으로 나누고 두 개의 다른 목록 상자에 표시하는 방법

Sauk

사용자가 링크 목록이있는 텍스트 파일을 업로드 할 수있는 프로그램을 작업 중이며 업로드가 성공하면 텍스트 파일의 줄이 두 개의 목록 상자로 나뉩니다. listbox1에는 텍스트 파일의 50 %, listbox2에는 나머지 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++;


            }


        }

이 코드는 텍스트 파일의 정확한 줄 수를 알고 있으면 잘 작동하지만 텍스트 파일이 줄을 적게 구성하면 예외가 발생합니다. 파일을 두 개의 동일한 부분으로 나누고 두 개의 목록 상자에 표시하려고합니다. 조언이나 제안을 부탁드립니다.

매트

배열 Length-property를 사용하십시오 text. 그 값은 배열의 구성원 (줄) 수와 같습니다.

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++;
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관