0

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.

4

3 回答 3

4

您可以使用以下方法:

 

    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();

 
于 2013-09-19T06:08:57.353 回答
0

您可以如下阅读所有行 // 假设所有行总是有 3 个值

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,
                                         });
      }

}

此代码是一个示例,必须检查数组长度等各种条件,也请检查

于 2013-09-19T05:50:06.597 回答
0

假设逗号永远不会出现在数据中:使用 StreamReader.ReadLine 读取每一行文本。对于每一行文本,使用 string.Split 将行拆分为字符串数组,使用逗号作为拆分字符。现在你有一个由 3 个字符串组成的数组,其中 [0] 是姓名,[1] 是电子邮件,而 [2] 是电话。

于 2013-09-19T05:56:08.370 回答