Question

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);
}
Was it helpful?

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

OTHER TIPS

Your code is assuming that the achCheckStr array has at least 2 elements without first checking how many there are. If the file exists & the contents are empty, achCheckStr.Length will be 0 and the IndexOutOfRangeException will be thrown exactly where it's happening.

Where are you storing "achievements.txt"? It could be in the wrong place, so the code would not find it.

You can fully qualify the path or put the file within the bin directory where the .exe is generated.

Here's a way

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);
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top