读取文本文件并将信息插入到新对象中 [英] Reading a text file and inserting information into a new object

查看:123
本文介绍了读取文本文件并将信息插入到新对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

所以我有一个文本文件,其中包含以下格式的信息,包括名称,电子邮件和电话号码。 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

当我的程序启动时,我想读取这个文件,并把每一行变成一个新的Person()最终添加到列表中。我想读取每一行,然后使用逗号分隔每个字符串放入Person()的构造函数,这是一个基本的类:

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





$ b

我已经做了一些观察,我认为使用streamreader是可行的阅读文本文件,但我不知道从哪里去。

解决方案

您可以使用以下方法:

  

字符串行;
List listOfPersons = new List();

//读取文件并逐行显示。
System.IO.StreamReader file =
new System.IO.StreamReader(@c:\yourFile.txt); ((line = file.ReadLine())!= null)
{
string [] words = line.Split(',');
listOfPersons.Add(new Person(words [0],words [1],words [2]));
}

file.Close();


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.

解决方案

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

 

这篇关于读取文本文件并将信息插入到新对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆