下面的代码有效,但每次都会引发异常消息框。消息框中显示“索引超出了数组的范围”。我希望看不到该消息框,但我也想不要有空的异常捕获。我做错了什么?为什么我得到的索引超出了数组异常的范围?
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);
}
}
}
}
================================== UPDATE ======== ================================== 阅读并添加PSL的代码后,我结束了一个新的例外(引用的对象没有设置为对象的实例
这是我的新代码,我改为while循环寻找null,并在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);
}
}
}
}
为了不被驴,但你尝试调试? – jerry 2013-05-08 03:08:21
我做过了,但我不明白,所以我来到这里,所以你会用英语向我解释。谢谢您的帮助。 – 2013-05-09 01:30:12
抛出新的空引用异常在哪里? – 2013-05-09 03:57:55