Array out of index when trying to read from a text file, and int32.tryparse

I'm getting an error that says I have an array out of index, but I'm not sure what I am doing wrong. I have commented out the line that Visual Studio has highlighted as the error. It happens in the ReadData() method. Thanks for any advice.

A first chance exception of type 'System.IndexOutOfRangeException' occurred in Lab3.exe An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Lab3.exe Additional information: Index was outside the bounds of the array. The program '[9140] Lab3.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

class Program
{
    private const int MAX_MEDIA_OBJECTS = 100; // Max number of array objects
    private int mediaCount = 0; // Counter to keep track of amount of media in Data.txt

    private Media[] media = new Media[MAX_MEDIA_OBJECTS];

    private Song[] songs = new Song[MAX_MEDIA_OBJECTS];
    private Movie[] movies = new Movie[MAX_MEDIA_OBJECTS];
    private Book[] books = new Book[MAX_MEDIA_OBJECTS];

    static void Main(string[] args)
    {
        Program lab3 = new Program();

        bool didUserExit = false;

        int userSelectedOption;

        lab3.ReadData();

        do // Do While loop for the options menu, exits when the user selects the exit option.
        {
            lab3.DisplayOptions();
            string userInput = Console.ReadLine();

            if (int.TryParse(userInput, out userSelectedOption))
            {
                lab3.ProcessSelectedInput(userSelectedOption, lab3);
            }
            else
            {
                lab3.DisplayErrorMessage();
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

        } while (!didUserExit);
    }

    public void ReadData()
    {
        // Opens the Data.txt file for read access
        FileStream mediaFile = new FileStream("Data.txt", FileMode.Open, FileAccess.Read);
        StreamReader mediaData = new StreamReader(mediaFile);

        string mediaRow; // Holds each media data per row

        while ((mediaRow = mediaData.ReadLine()) != null)
        {
            // Splits each row with the delimiter
            string[] mediaDataSplit = mediaRow.Split('|');

            // Temporary variables to hold media data
            int year;


            /** ERROR HAPPENS HERE ACCORDING TO VISUAL STUDIO IDE */
            bool didConvert = Int32.TryParse(mediaDataSplit[2].Trim(), out year);

            if (!didConvert)
            {
                Console.WriteLine("Improperly formated field at line {0}", mediaCount + 1);
                Environment.Exit(0);
            }

            if (didConvert)
            {
                Console.WriteLine("trace year {0}", mediaDataSplit[2]);
            }

            mediaCount++;
        }
    }

    public void ProcessSelectedInput(int userSelectedOption, Program labReference)
    {
        switch (userSelectedOption)
        {
            case 1:
                Console.WriteLine("case1");
                break;
            case 2:
                Console.WriteLine("case2");
                break;
            case 3:
                Console.WriteLine("case3");
                break;
            case 4:
                Console.WriteLine("case4");
                break;
            case 5:
                Console.WriteLine("case5");
                break;
            case 6:
                Environment.Exit(0);
                break;
            default:
                labReference.DisplayErrorMessage();
                break;
        }
    }

    public void DisplayOptions()
    {
            Console.Clear();

            Console.WriteLine("1. List All Books");
            Console.WriteLine("2. List All Movies");
            Console.WriteLine("3. List All Songs");
            Console.WriteLine("4. List All Media");
            Console.WriteLine("5. Search All Media by Title");
            Console.WriteLine("");
            Console.WriteLine("6. Exit Program");
            Console.WriteLine("");
            Console.Write("Enter choice: ");
    }

    public void DisplayErrorMessage()
    {
        Console.WriteLine("*** Invalid Choice - Try Again ***");
    }
}

Answers


The error is probably happening here: mediaDataSplit[2]

as a result from when you get it here: string[] mediaDataSplit = mediaRow.Split('|');

Whatever line it is looking at does not have as many "|" characters as you are expecting, so it is not creating as large of an array when it spits.

You should check what the value of mediaRow is when it is failing.


mediaDataSplit contains less than three elements or it's empty. Before you try to access the third element you can check whether or not the element exists:

if(mediaDataSplit.Length >= 3)
    bool didConvert = Int32.TryParse(mediaDataSplit[2].Trim(), out year);

Need Your Help

How can I test a PL/SQL function on a database where I do not have 'CREATE PROCEDURE' privileges?

sql database stored-procedures

I am trying to troubleshoot a PL/SQL stored procedure, written on a development database, that is malfunctioning on a production database. I use SQLdeveloper for all of my coding and testing.

Saving state that resides in POCO/DTO using Actor Model

akka poco dto orleans actor-model

I was looking for some use cases or code samples that illustrate how state that resides inside simple DTO/POCO model classes can be saved using the Actor Model that impelemnets the business logic.