下面的代码有效,但每次都会抛出一个异常消息框。消息框显示“索引超出了数组的范围”。我不想看到消息框,但我也不想有一个空的异常捕获。我做错了什么?
private void btnReadFile_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog oFD = new OpenFileDialog();
if (oFD.ShowDialog() == DialogResult.OK)
{
if ((myStream = oFD.OpenFile()) != null)
{
try
{
StreamReader sr = new StreamReader(myStream);
while (sr.Peek() >=0)
{
for (int i = 0; i < myStream.Length; i++)
{
string[] lines = sr.ReadLine().Split(new Char [] { '\t' }, StringSplitOptions.None);
string one = lines[0];
string two = lines[1];
string three = lines[2];
ListViewItem item = new ListViewItem(new string[] { one, two, three });
lvRollResults.Items.Add(item);
}
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
===================================更新=============== =============================在阅读和添加PSL的代码后,我最终得到了一个新的例外(未设置为引用的对象对象的实例。
这是我的新代码。我更改为 while 循环寻找空值,并在 while 循环内添加了一个 reaLine()。此代码现在可以正常工作,没有例外。
private void btnReadFile_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog oFD = new OpenFileDialog();
if (oFD.ShowDialog() == DialogResult.OK)
{
if ((myStream = oFD.OpenFile()) != null)
{
try
{
StreamReader sr = new StreamReader(myStream);
while ((sr.ReadLine()) != null)//if line is null stop reading
{
string[] lines = sr.ReadLine().Split(new Char[] { '\t' }, StringSplitOptions.None);
string one = lines[0];
string two = string.Empty;
string three = string.Empty;
if (lines.Length > 1)
two = lines[1];
if (lines.Length > 2)
three = lines[2];
ListViewItem item = new ListViewItem(new string[] { one, two, three });
lvRollResults.Items.Add(item);
sr.ReadLine();//read a line to see if it is null
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}