Search code examples
c#csvhelper

Csv Helper. First Value is shifting to the right


I have been trying to create a simple csv file using the csv helper. However, the result, I am getting is not what I expected. For some reason which I cannot find it, the first value is shifting towards the right and appear as the header.

Could someone point me what I am doing wrong here?

public class Record
{ 
    public string Vrm { get; set; }        
    public string Version { get; set; }
    public DateTime Started { get; set; }
    public DateTime? Completed { get; set; }
    public string Status { get; set; }
    public string Comments { get; set; }
}

static void Main(string[] args)
    {
        var source = new List<Record> {
            new Record {

                Status = "Success",
                Version = "enhance",
                Started = DateTime.Parse("2017-11-15 13:27:56.9933333"),
                Completed = DateTime.Parse("2017-11-15 13:27:57.7300000"),
                Vrm = "16aux",
                Comments = "Completed Successfully"
            }
        };

        var month = DateTime.UtcNow.Month;
        var year = DateTime.UtcNow.Year;
        var fileName = $"TestFile_{month}{year}.csv";

        using (var sw = new StreamWriter(fileName))
        {
            var writer = new CsvWriter(sw);

            try
            {
                writer.WriteHeader<Record>();
                foreach (var record in source)
                {
                    writer.WriteField(record.Vrm);
                    writer.WriteField(record.Version);
                    writer.WriteField(record.Started);
                    writer.WriteField(record.Completed);
                    writer.WriteField(record.Status);
                    writer.WriteField(record.Comments);
                    writer.NextRecord();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var i = sw;
        }            
    }

The result is something like this: Result of only one record

Result with two records


Solution

  • Read up on http://joshclose.github.io/CsvHelper/writing#writing-all-records

    You need to advance the writer one line by calling writer.NextRecord(); after writer.WriteHeader<Record>();.

    You could also simply write all data at once, using csv.WriteRecords( records ); instead of foreaching over them