首页 > 解决方案 > 试图从文本文件读入列表

问题描述

我创建了一个非常简单的类,我正在尝试使用 List 类从文本文件中读取到列表中。
我使用 StreamReader inputFile 打开文件,但是当我尝试使用 ReadLine 时出现错误,我无法将字符串转换为... .Bowler (这是我列表中的名称。

我创建了这个类,以便我可以从多个表单访问列表。我显然是 C# 的新手,并且是一般的编程新手。

//the ReadBowlers method reads the names of bowlers 
        //into the listBowlers.
        private void ReadBowlers(List<Bowler> listBowlers)
        {
            try
            {
                //Open the Bowlers.txt file.
                StreamReader inputFile = File.OpenText("Bowlers.txt");

                //read the names into the list
                while (!inputFile.EndOfStream)
                {
                    listBowlers.Add(inputFile.ReadLine());
                }

                //close the file.
                inputFile.Close();
            }
            catch (Exception ex)
            {
                //display error message
                MessageBox.Show(ex.Message);
            }

给我错误的行是:listBowlers.Add(inputFile.ReadLine());

标签: c#

解决方案


您可以创建一个string从文件中读取并返回Bowler.

例如,假设您的数据行如下所示:

鲍勃·史密斯,5,XYZ

public Bowler Parse(string inputLine)
{
    // split the line of text into its individual pieces
    var lineSegments = inputLine.Split(',');

    // create a new Bowler using those values
    var result = new Bowler
    {
        Name = lineSegments[0],
        Id = lineSegments[1],
        SomeOtherBowlerProperty = lineSegments[2]
    }
    return result;
}

现在你可以这样做:

var line = inputFile.ReadLine();
var bowler = Parse(line);
listBowlers.Add(bowler);

但它变得更好!如果Bowler有很多属性怎么办?如果您不想跟踪每列的位置怎么办?

CsvHelper是一个很棒的 Nuget 包,我相信还有其他人喜欢它。他们让我们使用别人测试过的代码,而不是自己编写。(我没有带头,因为先写它是一种很好的学习方式,但是学习使用可用的东西也很好。)

如果您的数据有列标题,CsvHelper 将为您找出哪些列包含哪些属性。

因此,假设您在文件中有这些数据:

名字,姓氏,Id,开始日期
Bob,Smith,5,1/1/2019
John,Galt,6,2/1/2019

而这堂课:

public class Bowler
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? StartDate { get; set; }
}

您可以编写以下代码:

public List<Bowler> GetBowlersFromFile(string filePath)
{
    using(var fileReader = File.OpenText(filePath))
    using (var reader = new CsvReader(fileReader))
    {
        return reader.GetRecords<Bowler>().ToList();
    }
}

它查看标题行并确定哪一列是哪一列。


推荐阅读