Search code examples
c#arraysexceptionfile.readalllines

IndexOutOfRange exception


Why is this giving a IndexOutOfRange exception?

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

Solution

  • Problem 1:

    there mightbe no file exists with name achievements.txt. this statement string[] achCheckStr = File.ReadAllLines("achievements.txt"); might be returning null.

    Solution 1: so before accessing any files please check whether file exists or not by using File.Exists() method.

    Problem 2: there might be no lines in your text file.

    Solution 2: before accessing the string array which contains lines please make sure that it is not empty by checking its Length

    Try This:

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