c# - 试图从文本文件读入列表
问题描述
我创建了一个非常简单的类,我正在尝试使用 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());
解决方案
您可以创建一个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();
}
}
它查看标题行并确定哪一列是哪一列。
推荐阅读
- android-studio - 在android studio中折叠应用栏后的自定义工具栏
- javascript - 在我从具有整套 HTMLCollection 的另一个数组复制后,按钮数组为空
- reactjs - 如何在 react 中使用 react-bootstrap 导入 Sass
- pandas - 如何在 k-means 之前对银行帐号进行编码?
- bash - Bash:查找具有多个 -name 变量的命令
- google-sheets - 谷歌表格:投资策略的数学问题
- python - 在 Python 中替换异常值的四分位数规则
- ios - 使用 Swift/Objective-C 减少色带以从最多 200 个视频帧创建 GIF
- node.js - 在基于 Electron 的应用程序中切换浏览器
- c++ - 为什么 std::map::operator[] 赋值需要一个无参数的构造函数?