2014-03-18 37 views
0

爲什麼這給出IndexOutOfRange異常?IndexOutOfRange異常

string[] achCheckStr = File.ReadAllLines("achievements.txt"); 

if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs 
{ 
    setAchievements(1); 
} 
if (achCheckStr[1] == ach2_Faster) 
{ 
    setAchievements(2); 
} 
+3

是否驗證你實際上得到使用調試器中的文件的內容? –

+0

添加此:if(achCheckStr!= null)在我之前(achCheckStr [0] == .... – mok

+0

添加一個斷點並確認'achCheckStr'有數據... – sab669

回答

1

問題1:

有mightbe沒有文件存在與名achievements.txt。 此聲明string[] achCheckStr = File.ReadAllLines("achievements.txt");可能會返回null

解決方案1:因此在訪問任何文件之前,請使用File.Exists()方法檢查文件是否存在。

問題2:您的文本文件中可能沒有行。

解決方案2:之前訪問字符串數組,它包含線,請確保它不爲空通過檢查其Length

試試這個:

if(File.Exists("achievements.txt")) 
{ 
    string[] achCheckStr = File.ReadAllLines("achievements.txt"); 
    if(achCheckStr.Length > 0) 
    { 
     if (achCheckStr[0] == ach1_StillBurning) 
     { 
      setAchievements(1); 
     } 
     if (achCheckStr[1] == ach2_Faster) 
     { 
      setAchievements(2); 
     } 
    } 
} 
0

你的代碼假設achCheckStr數組至少有2個元素沒有首先檢查有多少。如果文件存在&內容爲空,則achCheckStr.Length將爲0,並且IndexOutOfRangeException將在其發生的位置發生。

0

你在哪裏存儲「的成就。文本」?它可能在錯誤的地方,所以代碼不會找到它。

您可以完全限定路徑或將文件放在生成.exe的bin目錄中。

0

這裏是一種

string[] achCheckStr = File.ReadAllLines("achievements.txt"); 
     if (achCheckStr != null && achCheckStr.Any()) 
     { 

      if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs 
      { 
       setAchievements(1); 
      } 
      if (achCheckStr[1] == ach2_Faster) 
      { 
       setAchievements(2); 
      } 
     } 
相關問題