问题
So I have a text file with information in the following format, with the name, email, and phone number.
Bill Molan, Bill.Molan@gmail.com, 612-789-7538
Greg Hanson, Greg.Hanson@gmail.com, 651-368-4558
Zoe Hall, Zoe.Hall@gmail.com, 952-778-4322
Henry Sinn, Henry.Sinn@gmail.com, 651-788-9634
Brittany Hudson, Brittany.Hudson@gmail.com, 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.
回答1:
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();
回答2:
Assuming that the comma will never appear within the data: Use StreamReader.ReadLine to read each line of text. With each line of text, use string.Split to split the line into an array of strings using the comma as the split character. Now you have an array of 3 strings where [0] is the name, [1] the email, and [2] the phone.
回答3:
You can read all lines as below // assuming all lines will have 3 values always
var allLines = File.ReadAllLines(path);
var listOfPersons = new List<Person>();
foreach(var line in allLines)
{
var splittedLines = line.Split(new[] {","})
if(splittedLines!=null && splittedLines.Any())
{
listOfPersons.Add( new Person {
Name = splittedLines[0],
Email = splittedLines .Length > 1 ?splittedLines[1]:null,
Phone = splittedLines .Length > 2? splittedLines[2]:null,
});
}
}
this code is a sample must be checked for various conditions like array length etc also please check the
来源:https://stackoverflow.com/questions/18886945/reading-a-text-file-and-inserting-information-into-a-new-object