Search code examples
c#filehelpers

Filehelpers - Export with double quotes around each field EXCEPT when field is blank/null


I may have missed the answer when searching but I have a file that needs all fields double quoted EXCEPT when a field is blank, missing or null then only the comma will be entered.

I'm using [FieldQuoted('"', QuoteMode.AlwaysQuoted)] with the sample following output:

"Mary","Smith","555-555-5555","","1234","","3141 Pi Cr."

But I need the output to actually look like this:

"Mary","Smith","555-555-5555",,"1234",,"3141 Pi Cr."

Any suggestions using Filehelpers?


Solution

  • You can use an INotifyWrite event to modify the output before writing to the file.

    For instance

    [DelimitedRecord(",")]
    class Product : INotifyWrite // <-- implement events
    {
        [FieldQuoted(QuoteMode.AlwaysQuoted)]
        public string Name;
        [FieldQuoted(QuoteMode.AlwaysQuoted)]
        public string Description;
        [FieldQuoted(QuoteMode.AlwaysQuoted)]
        public string Size;
    
        public void BeforeWrite(BeforeWriteEventArgs e)
        {
        }
    
        public void AfterWrite(AfterWriteEventArgs e)
        {
            // replace any occurrences of ,"", with ,,
            e.RecordLine = e.RecordLine.Replace(",\"\",", ",,");
        }
    }