Reputation: 117
I have csvFile's structured like so:
val1,val2,val3
1,2,4
.
.
val1,val2,val3
3,7,8
and
val1,val2,val3
1,2,4
.
.
val1,val2,val3
3,7,8
.
.
val1,val2,val3
11,5,9
For this, the csv headers all have the same name.
With that, my question is, how would I skip all the way down to the very last table/dataset? So to get tables:
//first csvFile
val1,val2,val3
3,7,8
//second csvFile
val1,val2,val3
11,5,9
What I've done so far is implement
for (var i = 0; i < 7; i++)//skip number of lines
{
csv.Read();//function here skips line to get to real header
}
csv.Read();
csv.ReadHeader();
With this, I can skip lines all the way down, but that is only provided that I know the spacing to get to the line that I want to, so it is very file specific. How would it be implemented so you can always get the last Header values for a csvFile without taking in consideration the number of lines?
I am also using the open source library, CsvHelper
Upvotes: 0
Views: 187
Reputation: 74605
CsvHelper will read from a Reader. Readers can read from strings. We can thus preprocess the file like this:
var sb as new StringBuilder();
foreach(var line in File.ReadLines("path"){
if(line == "val1,val2,val3")
sb.Clear();
sb.AppendLine(line);
}
using (var reader = new StringReader(sb.ToString()))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<...>();
}
If the val1,val2,val3
will change their order, presentation, spaces etc then you could make the headers into an array of strings and then ask whether a line contained all the headers:
var headers = "val1 val2 val3".Split();
//and in the loop
if(headers.All(h => line.Contains(h)))
...
Upvotes: 1