Search code examples
c#escapingexport-to-csvstring-interpolation

Escape semicolon in interpolated string C#


I am writing data to .csv file and I need the below expression to be read correctly:

csvWriter.WriteLine($"Security: {sec.ID} ; Serial number: {sec.SecuritySerialNo}"); 

the semicolon in between is used to put the serial number in a separate cell.

The problem is that ID can also contain semicolons and mess up the data, therefore I need to escape it.

I have tried to use replace:

csvWriter.WriteLine($"Security: {sec.ID.Replace(";", "")} ; Serial number: {sec.SecuritySerialNo}"); 

though deleting semicolons is not what I want to achieve, I just want to escape them.


Solution

  • Let's emphasize again that the best way to create a CSV file is through a specialized CSV Parser library.
    However, just to resolve the simple case presented by your question you could add double quotes around each field. This should be enough to explain to the Excel parser how to handle your fields.

    So, export the fields in this way:

    csvWriter.WriteLine($"\"Security: {sec.ID}\";\"Serial number: {sec.SecuritySerialNo}\""); 
    

    Notice that I have removed the blank space around the semicolon. It is important otherwise Excel will not parse the line correctly