【问题标题】:Trying to read from text file into List<class>试图从文本文件读入 List<class>
【发布时间】:2019-04-30 01:59:25
【问题描述】:

我创建了一个非常简单的类,我正在尝试使用 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());

【问题讨论】:

  • 程序不知道如何将字符串转换为您的类。您需要告诉它如何手动执行此操作。您可以发布您的Bowler 课程吗?
  • 您试图以错误的方式使用文件流。建议阅读https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.7.2
  • @Loocid My Bowler Class code class Bowler { //fields private string _name; //构造函数 public Bowler() { _name = Name; } //名称属性 public string Name { get;放; }code
  • 我显然不太擅长这个,55岁开始学习
  • 如果您尝试将对象(Bowler)数据存储到磁盘并读回 - 研究序列化。在 4 或 5 行代码中保存或加载数据。

标签: c#


【解决方案1】:

您可以创建一个从您的文件中读取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、开始日期
鲍勃,史密斯,5,1/1/2019
约翰,高尔特,2019 年 6 月 2 日 1 日

还有这个类:

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

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

【讨论】:

    【解决方案2】:

    ReadLine() 为您提供字符串,因此您不能直接将其分配给自定义类,除非指定显式转换。

    最好创建一个新的 Bowler 实例,通过单独解析字符串来分配其值,然后将该实例添加到列表中。

    【讨论】:

    • 抱歉,您能解释一下如何“创建一个新的 Bowler 实例”吗?
    • var b = new Bowler() { Name = inputFile.ReadLine() };
    • 我试过了,也许我在错误的地方使用它,但它没有解决我遇到的错误。
    • inputFile.ReadLine() 最好在单独的行中初始化之前完成。这样,您还可以找到错误的确切原因。也许像 var line = inputFile.ReadLine();然后 var b = new Bowler() { Name = line };
    【解决方案3】:
    //the ReadBowlers method reads the names of bowlers 
        //into the listBowlers.
        private void ReadBowlers(List<Bowler> listBowlers)
        {
            try
            {
                //Open the Bowlers.txt file.
                string path = @"Bowlers.txt";
    
                //read the names into the list
    
                using (FileStream fs = File.OpenRead(path))
                {
                    byte[] b = new byte[1024];
                    UTF8Encoding temp = new UTF8Encoding(true);
                    while (fs.Read(b,0,b.Length) > 0)
                    {
                        listBowlers.Add(temp.GetString(b));
                    }
                }
    
            }
            catch (Exception ex)
            {
                //display error message
                MessageBox.Show(ex.Message);
            }
        }
    

    【讨论】:

    • 你能解释一下吗:使用 (FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true);我不想使用我不理解的东西。
    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2014-05-04
    相关资源
    最近更新 更多