Reputation:
I am making a number to music note value converter from text files and I am having trouble parsing text files in my C# code. The stream reader or parser seems to ignore every first line of text from different text files, I am learning from parsing CSV and assumed that I can parse text files the same way that I can parse CSV files. Here is my code:
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;
}
Here are the first 4 lines of one of my text file:
0.1|0.0|
0.0|0.1|
0.3|0.0|
0.1|0.0|
So every time that I have an output it will always skip the first line and move onto the next line. After it misses the first line it converts all the other values perfectly.
I have tried using a foreach loop but I end up getting an 'Index Out Of Range Exception'. Am I missing something/being stupid? Thanks for your time
Upvotes: 1
Views: 278
Reputation: 186688
In order to avoid such errors (erroneous reader.ReadLine()
in the beginning) get rid of Reader
s at all and query file with Linq (let .Net open and close the file, read it line after line and do all low level work for you):
using System.IO;
using System.Linq;
...
static List<NoteColumns> ReadNoteValues(string fileName) {
return File
.ReadLines(fileName)
.Where(line => !line.StartsWith('-'))
.Select(line => line.Split('|'))
.Select(cols => {
var noteColumn = new NoteColumns();
if (double.TryParse(cols[0], out var col))
noteColumn.QCol = col;
if (double.TryParse(cols[1], out var col))
noteColumn.WCol = col;
return noteColumn;
})
.ToList();
}
Upvotes: 1
Reputation: 2927
It's because you have already added ReadLine()
before the while loop which skips the first line
Upvotes: 4
Reputation: 20995
You have a call to reader.ReadLine();
before your loop, which you don't assign to anything
Upvotes: 4