简体   繁体   中英

Don't understand why I'm getting an IndexOutOfRangeException

I am trying to load in data field names into my program from a text file, and store them into a variable, an array.

The field names are to be used to sort and print data from other files into an organized new document.

I'm having a lot of trouble specifically with storing the fields from the file into an array.

The data fields text file is organized in a list manner, with each field being on its own row.

I went with creating a while loop that runs until the Peek() of the StreamReader is equal to -1.

I nested a for loop within the while loop that increments the index integer variable by 1 until it's less than or equal to the total amount of rows in the text file.

It also uses ReadLine() to store a row of the text document into the array at the specific index. I thought using that in the for loop would cycle through each row and store what it needs to store.

I will need to use the fields within a dictionary so that I can use the fields as keys and the data from other documents as the values for the dictionary when I get around to displaying that information.

I thought the way I had done it would have the necessary measures to avoid the IndexOutOfRangeException, but I guess that is not the case.

I would appreciate anyone willing to help me with this. I apologize if anything is unclear and will try to clarify things if need be.

If my attempted logic explanation was terrible, here's the code:

    class Program
{
    protected static string[] dataFields = new string[] { };

    static void Main(string[] args)
    {
        int iIndex;

        using (StreamReader titleStream = new StreamReader(@"..\..\DataFieldsLayout.txt"))
        {
            while (titleStream.Peek() > -1)
            {
                for (iIndex = 0; iIndex <= 150; iIndex++)
                {
                    // where the exception occurs
                    dataFields[iIndex] = titleStream.ReadLine();
                }
            }
        }

        // test
        Console.WriteLine(dataFields[0]);
        Console.WriteLine(dataFields[1]);
        Console.WriteLine(dataFields[2]);
        Console.WriteLine(dataFields[3]);
        Console.WriteLine(dataFields[4]);
    }
}

This is because when you define an array you have to make room for each element. So, when you declare the array as you have done you are not giving it any space to accept new data. You might want to declare your array in the following way (so that it has enough space for all of the data):

protected static string[] dataFields = new string[151];

You are reading up to 151 elements (because your <= 150 condition), so you want to give the appropriate amount of space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM