0

I have a simple text file that contains CSVs in the form of:

First Name, Last Name, Gender, Age, Email, Occupation.

I am reading this file into C# and then trying to split the properties by the comma and then append each piece of information to a Person class. Here is my code:

using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleProject
{
    class Program
    {
        static void Main()
        {
            // Text file location
            string fileLocation = @"C:\Users\naugh\Desktop\Example.txt";

            // Opens file, removes quotes and rewrites file
            string allText = File.ReadAllText(fileLocation);
            string allTextNoQuotes = allText.Replace("\"", "");
            File.WriteAllText(fileLocation, allTextNoQuotes);

            // Creates a list entry for each line in file
            List<string> peopleList = System.IO.File.ReadAllLines(fileLocation).ToList();
            
            // Blank Person list
            List<Person> people = new List<Person>();

            foreach (string person in peopleList)
            {
                string[] entries = person.Split(",");

                Console.WriteLine(entries[1]);

                /*person1.FirstName = entries[0];
                person1.LastName = entries[1];
                person1.Gender = entries[2];
                person1.Age = entries[3];
                person1.Email = entries[4];
                person1.Occupation = entries[5];

                people.Add(person1);*/
            }           
        }
    }
}

As a test, I am printing entries[1] which prints all of the Last Names to my terminal. However, after it prints the last name I get the following error:

Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.

When I try and implement the code to add the information to the Person class (that is commented out), it returns the same error.

Is anyone able to shed some light please?

zhulien
  • 5,145
  • 3
  • 22
  • 36
sonodan
  • 41
  • 1
  • 6
  • "after it prints the last name" - you're saying that it *does* print the last name (from `Console.WriteLine(entries[1])`) and the exception is thrown after that? Whichever line comes after that one doesn't have 5 commas. – Stroniax Mar 13 '21 at 20:31
  • Try if there is not any empty row (line) in your csv file. I can find them often in the end of files. Maybe you should test if your string person is (not) empty row by `string.IsNullOrEmpty(person);` – Vít Bednář Mar 13 '21 at 20:32
  • 1
    `List peopleList = System.IO.File.ReadLines(fileLocation).Where(line => !string.IsNullOrWhiteSpace(line)).ToList();` – Dmitry Bychenko Mar 13 '21 at 20:33
  • try check your example file , maybe some line have no , char and the entries array have only 1 value and the call for the second cell comes out for a not exist value – Michael Gabbay Mar 13 '21 at 20:36

0 Answers0