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