Reputation: 1
I need validate date range between first and last row in csv file.
How to read first and last row using CsvHelper without reading all lines?
Regards
Upvotes: 0
Views: 1114
Reputation: 1
I solved my problem.
I read the first line using CsvReader and standard GetRecord method.
The last line I read as a string using ReverseLineReader from @Jon Skeet answer.
Then I put this string in StringReader and next to CsvReader, then read the record using GetRecord method.
I hope someone will find it useful someday.
Regards katanisk8
Upvotes: 0
Reputation: 9074
I don't know that it is possible to only read the first and the last lines. You can at least limit the amount of data you bring into memory.
void Main()
{
using (var reader = new StringReader("Id,Name,RowDate\n1,First,7/1/2022\n2,Middle,7/15/2022\n3,Last,7/31/2022"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
DateTime first;
DateTime last = DateTime.MinValue;
csv.Read();
csv.ReadHeader();
csv.Read();
first = csv.GetField<DateTime>("RowDate");
while (csv.Read())
{
last = csv.GetField<DateTime>("RowDate");
}
Console.WriteLine($"First: {first}");
Console.WriteLine($"Last: {last}");
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime RowDate { get; set; }
}
Upvotes: 3