2017-02-02 39 views
2

我沒有寫入任何數組長度,但是當我嘗試讀取.csv文件時,我得到的「索引超出了數組的邊界」錯誤。 .csv文件大約是1 000 000行。有沒有人修復這些代碼?Streamreader和「索引超出了數組邊界」錯誤

.csv文件行如下所示。

0000000,26.0000000000000,38.0000000000000,30.01.2017,0,0,0 ,,, 0,0,0,0,0,0,0

string[] read; 
char[] seperators = { ',' }; 


     try 
     { 
      Image img = Image.FromFile(txtFilePath.Text); 
      Graphics g = Graphics.FromImage(img); 
      pictureBox1.Image = img; 
      pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; 

      StreamReader sr = new StreamReader(txtFile2Path.Text); 

      string data; 

      while ((data=sr.ReadLine()) !=null) 
      { 
       read = data.Split(seperators, StringSplitOptions.None); 

       float x = float.Parse(read[1]); 
       float y = float.Parse(read[2]); 
       string z = read[10]; 
      } 
     } 


     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     }  
+0

在調試模式看看這行'float x = float.Parse(read [1]); float y = float.Parse(read [2]); string z = read [10];' –

+0

如果read.Length> = 11,您可能想要有一個if條件 – Ben

+0

調試模式下這些行中沒有錯誤。在調試模式下,所有東西在visual studio中看起來都是正確的。 – Burak

回答

1

只是爲了澄清這個結果在這裏的任何人的答案..

 while ((data=sr.ReadLine()) !=null) 
     { 
      read = data.Split(seperators, StringSplitOptions.None); 
      if (read.Length >= 11) 
      { 
       float x = float.Parse(read[1]); 
       float y = float.Parse(read[2]); 
       string z = read[10]; 
      } 
     } 

當訪問一個數組可能不是所需的長度,首先檢查它。

當一行代碼試圖訪問在陣列中不存在的項目(N-1)的Index was outside the bounds of the array異常將只被拋出 - 由於具有比(N)項更少的陣列

相關問題