2013-05-08 39 views
-2

下面的代码有效,但每次都会引发异常消息框。消息框中显示“索引超出了数组的范围”。我希望看不到该消息框,但我也想不要有空的异常捕获。我做错了什么?为什么我得到的索引超出了数组异常的范围?

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

    } 
+1

为了不被驴,但你尝试调试? – jerry 2013-05-08 03:08:21

+0

我做过了,但我不明白,所以我来到这里,所以你会用英语向我解释。谢谢您的帮助。 – 2013-05-09 01:30:12

+0

抛出新的空引用异常在哪里? – 2013-05-09 03:57:55

回答

1

看起来好像是数组lines没有3个元素。不要尝试访问大于或等于数组长度的数组索引。

1

你做错了在这个地方。

string[] lines = sr.ReadLine().Split(new Char [] { '\t' }, StringSplitOptions.None); 

string one = lines[0]; 
string two = lines[1]; 
string three = lines[2]; 

甚至没有检查lines arraylength你正试图将项目出来。这也一定是您接收错误的地方。如果您正在阅读的文章中少于2 \t,该怎么办?这会因Index out of bounds而失败。

相反,你可以做的是

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];