【发布时间】:2018-07-20 14:14:01
【问题描述】:
我正在从文本文件制作一个数字到音符值转换器,但在我的 C# 代码中解析文本文件时遇到问题。流阅读器或解析器似乎忽略了来自不同文本文件的每一行文本,我正在从解析 CSV 中学习,并假设我可以像解析 CSV 文件一样解析文本文件。这是我的代码:
static List<NoteColumns> ReadNoteValues(string fileName)
{
var allNotes = new List<NoteColumns>();
using (var reader = new StreamReader(fileName))
{
string line = "";
reader.ReadLine();
while ((line = reader.ReadLine()) != null)
{
string[] cols = line.Split('|');
var noteColumn = new NoteColumns();
if (line.StartsWith("-"))
{
continue;
}
double col;
if (double.TryParse(cols[0], out col))
{
noteColumn.QCol = col;
}
if (double.TryParse(cols[1], out col))
{
noteColumn.WCol = col;
}
}
}
return allNotes;
}
这是我的一个文本文件的前 4 行:
0.1|0.0|
0.0|0.1|
0.3|0.0|
0.1|0.0|
所以每次我有输出时,它总是会跳过第一行并移动到下一行。在错过第一行之后,它会完美地转换所有其他值。
我曾尝试使用 foreach 循环,但最终得到“索引超出范围异常”。我错过了什么/愚蠢吗?感谢您的宝贵时间
【问题讨论】:
-
在循环之前去掉
reader.ReadLine。 -
reader.ReadLine() 在循环之前
-
如果您为某些 CSV 解析算法复制了该代码,则
reader.ReadLine之前的while循环很可能故意跳过第一行,因为它预计这是列的标题行.