1

I have a lot of CSV files without header and need to read it in C#. I manually added header to one of these files and with the following code using CSVHelper I can read the files and show them in a GridView.

Now my question is, how can I read these files without a header? Or how can I add a header (a new record) using CSVHelper in the first line?

 public Form1()
    {
        InitializeComponent();
        List<Festival> records;
        var config = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ";" };
        using (var reader = new StreamReader(@"File8.csv"))
            using(var csv = new CsvReader(reader, config))
        {
            records = csv.GetRecords<Festival>().ToList();
        }
        
        dataGridView1.DataSource = records;
    }

Class

 public class Festival
{
    public string Day { get; set; }
    public string Start { get; set; }
    public int Lenght { get; set; }
    public string FilmName { get; set; }
    public float Rating { get; set; }
}

csv sample

Mi;22:15;110;A;8
Mi;19:00;106;B;8
Mi;19:15;97;C;8.2
2

1 Answer 1

11

Add column-index mapping attributes to the target members:

public class Festival
{
    [Index(0)]
    public string Day { get; set; }

    [Index(1)]
    public string Start { get; set; }

    [Index(2)]
    public int Lenght { get; set; }

    [Index(3)]
    public string FilmName { get; set; }

    [Index(4)]
    public float Rating { get; set; }
}

And specify HasHeaderRecord = false in the config:

var config = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ";", HasHeaderRecord = false };

If modifying the target model isn't desirable, implement a ClassMap instead:

public sealed class FestivalMap : ClassMap<Festival>
{
    public FestivalMap()
    {
        Map(f => f.Day).Index(0);
        Map(f => f.Start).Index(1);
        Map(f => f.Lenght).Index(2);
        Map(f => f.FilmName).Index(3);
        Map(f => f.Rating).Index(4);
    }
}

And register it like this before fetching the records (you still need to specify HasHeaderRecord = false in the config):

csv.Context.RegisterClassMap<FestivalMap>();
records = csv.GetRecords<Festival>().ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.