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?