Search code examples
c#file-ioseparator

Reading a text file and inserting information into a new object


So I have a text file with information in the following format, with the name, email, and phone number.

Bill Molan, [email protected], 612-789-7538
Greg Hanson, [email protected], 651-368-4558
Zoe Hall, [email protected], 952-778-4322
Henry Sinn, [email protected], 651-788-9634
Brittany Hudson, [email protected], 612-756-4486

When my program starts, I want to read this file and make each row into a new Person(), which I will eventually add to a list. I am wanting to read each line, and then use the comma to separate each string to put into the constructor of Person(), which is a basic class:

public PersonEntry(string n, string e, string p)
{
    Name = n;
    Email = e;
    Phone = p;
}

I have done some looking and I think that using a streamreader is going to work for reading the text file, but I'm not really sure where to go from here.


Solution

  • You can use the following method:

     
    
        string line;
        List listOfPersons=new List();
    
        // Read the file and display it line by line.
        System.IO.StreamReader file = 
            new System.IO.StreamReader(@"c:\yourFile.txt");
        while((line = file.ReadLine()) != null)
        {
            string[] words = line.Split(',');
            listOfPersons.Add(new Person(words[0],words[1],words[2]));
        }
    
        file.Close();