Reputation: 21
I am using CSVHelper (https://github.com/JoshClose/CsvHelper/blob/master/src/CsvHelper/Configuration/IReaderConfiguration.cs) to read a csv file and I want to skip a certain number of rows from the beginning of the file. Is it possible to use "ShouldSkipRecord" in order to achieve that?
Upvotes: 2
Views: 5849
Reputation: 1
Below is working and tested:
// * Below config will remove those top rows start with comments
// (start with '#') and avoid parsing error on .ToList().
var config = new CsvConfiguration(CultureInfo.InvariantCulture) {
ShouldSkipRecord = (row) => row.Row[0].StartsWith("#")
};
IEnumerable<Foo> records = new List<Foo>();
using (var reader = new StreamReader("CsvFilePath"))
{
using (var csv = new CsvReader(reader, config))
{
records = csv.GetRecords<Foo>().ToList();
}
}
if(records != null && records.Count() > 0)
{
// ...
}
Upvotes: 0
Reputation: 164
Below is what worked for me:
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldSkipRecord = (row) =>
{
//your logic for skipping records goes here
return (string.IsNullOrEmpty(row.Record[7]);
}
};
using (var reader = new StreamReader("CsvFilePath"))
using (var csv = new CsvReader(reader, config))
{
lst = csv.GetRecords<Foo>().ToList();
}
Upvotes: 0
Reputation: 9064
You could use ShouldSkipRecord
if you know that the rows all start with say a certain character.
public class Program
{
public static void Main(string[] args)
{
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
using (CsvReader csv = new CsvReader(reader))
{
writer.WriteLine("# Something here.");
writer.WriteLine("# Another line we don't need.");
writer.WriteLine("Id,Name");
writer.WriteLine("1,George");
writer.Flush();
stream.Position = 0;
csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("#");
var records = csv.GetRecords<Foo>().ToList();
}
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
If you know you want to skip say the first 2 rows, this would work.
public class Program
{
public static void Main(string[] args)
{
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
using (CsvReader csv = new CsvReader(reader))
{
writer.WriteLine("Something here.");
writer.WriteLine("Another line we don't need.");
writer.WriteLine("Id,Name");
writer.WriteLine("1,George");
writer.Flush();
stream.Position = 0;
for (int i = 0; i < 2; i++)
{
csv.Read();
}
var records = csv.GetRecords<Foo>().ToList();
}
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Upvotes: 5