Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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.
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.
Both examples call Flush() method of StreamWriter because otherwise buffer is not filled when code creates CSV string.
- Generating CSV-files on .NET (Gunnar Peipman)