Search code examples
filehelpers

Last Delimiter in CSV file with FileHelpers


I must develop a CSV-Export with 57 columns.

After the last column i need the delimiter and then the LFCR.

Example:

Now i have

aaaa;bbbb;cccc;dddd

But i need

aaaa;bbbb;cccc;dddd;

Which attribute can control this?


Solution

  • Not sure if you can do this with an attribute, but you can with the AfterWriteRecord event

    example

    void Main()
    {
        var records = new List<Record>();
        records.Add(new Record() { A = "aaaa", B = "bbbb", C = "cccc", D = "dddd" });
    
        var engine = new FileHelperEngine<Record>();
        engine.HeaderText = engine.GetFileHeader();
    
        engine.AfterWriteRecord += AfterWriteEvent;
        engine.WriteFile("output.csv", records);                
    }
    
    void AfterWriteEvent(EngineBase engine, AfterWriteEventArgs<Record> e)
    {
        e.RecordLine += ";" ;
    }
    
    [FileHelpers.DelimitedRecord(";")] 
    public class Record
    {    
        public string A;
        public string B;
        public string C;
        public string D;
    }
    

    outputs

    A;B;C;D 
    aaaa;bbbb;cccc;dddd;