Reading a text file and inserting information into a new object

帅比萌擦擦* 提交于 2019-11-30 10:39:22

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

 

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!