Search code examples
c#.netcsvhelper

How can I add my CSVHelper delimiter to the beginning of each record


I am using CSVHelper to create a pipe delimited file that has dozens of objects that are being mapped and written. The requirement includes having the pipe character at the beginning and end of each record so the output would look something like this:

|SYSTEM|5|123456789|A003|07/08/1992 00:00|00301fJ|11/14/2023 08:47|33291|11/14/2023 08:47|33291|

|SYSTEM|7|123456789|B005|555-55-5555|00301fJ|11/14/2023 08:47|33291|11/14/2023 08:47|33291|

|SYSTEM|9|123456789|B005||CA|01/01/0001 00:00|00301fJ|11/14/2023 09:22|33291|11/14/2023 09:22|33291|

|SYSTEM|11|123456789|C1234||CA|00301fJ|11/14/2023 09:22|33291|11/14/2023 09:22|33291|

|SYSTEM|13|123456789|H003|||||||00301fJ|11/14/2023 09:22|33291|11/14/2023 09:22|33291|

I have tried to manually add the leading and trailing pipe character manually like this:

foreach(var record in myList)
{
    csv.WriteField(config.Delimiter, shouldQuote: false);
    csv.WriteRecord(record);
    csv.WriteField(config.Delimiter, shouldQuote: false);
    csv.NextRecord();
}

but that duplicates the pipe characters. Does anyone have a suggestion on how I can do this?


Solution

  • I have applied suggestion from comment to fix the issue.

    You could fix by replacing config.Delimiter used by string.Empty.

    Modified Code:

    foreach (var record in myList)
    {
        csvwriter.WriteField(string.Empty, shouldQuote: false);
        csvwriter.WriteRecord(record);
        csvwriter.WriteField(string.Empty, shouldQuote: false);
        csvwriter.NextRecord();
    }