Writing CSV files using C#


CSV files with C#

This example introduces how to generate CSV files with C#. It uses NuGet package CsvHelper to accomplish a goal. CsvHelper is powerful but easy to use library that supports most important .NET Framework types. It is possible to write CSV-files with custom structure and it is also possible to register types and let library to convert them to CSV automatically.

Writing objects to CSV

Let's see first how to dump simple projects array to CSV. This is shortest I was able to invent to have CSV-file with headers row.

Click Run to see the demo

Objects with fields

There is one special case - class with fields. Sometimes public fields are used instead of properties because property means two methods and one backing field. If there's no real need for properties then data migration applications often use public fields to keep objects smaller. This is something that CsvHelper does not support directly.

Click Run to see the demo

Both examples call Flush() method of StreamWriter because otherwise buffer is not filled when code creates CSV string.


Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to