c# 如何将文本文件的行分成两等份,并在两个不同的列表框中显示

标签 c# .net winforms listbox

我正在开发一个程序,用户可以在其中上传带有链接列表的文本文件,上传成功后,文本文件的行分为两个列表框,其中 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++;


            }


        }

当我知道文本文件中确切的行数时,这段代码工作正常,但当文本文件包含较少的行时,它会抛出异常。我试图将文件分成两个相等的部分并将其显示在两个列表框中。请有任何意见或建议。

最佳答案

使用 text 数组的 Length 属性。它的值等于数组中成员(行)的数量:

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

关于c# 如何将文本文件的行分成两等份,并在两个不同的列表框中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22913228/

相关文章:

c# - 如何通过代码优先全局更改小数点的精度和小数位?

c# - OpenFileDialog C# 的默认名称?

winforms - Windows 窗体应用程序的物理中间层分离

winforms - TextBox C#中的Max Char?

c# - javascript通过后面的代码确认

c# - 避免在 DbParameter.Value 中装箱?

c# - 在 Linq-to-SQL 中映射 UDF 有任何灵活性吗?

c# - 格式化文件中的文本表,将每行两行合并为一行

c# - Azure 上的管道读取失败

.net - WebBrowser(WPF 和 WinForms 控件)和 JSON 对象 - JSON 未定义