Convert List to CSV in C# With Example

watch_later 1/17/2025

Converting a list to a CSV file in C# is a common requirement in software development, especially when exporting data for reports or data sharing. This article provides a detailed, step-by-step tutorial on how to efficiently convert a list to a CSV file in C#.

Why Convert a List to a CSV File?

CSV (Comma-Separated Values) is a widely used file format for storing tabular data. It’s lightweight, human-readable, and easy to process programmatically. Exporting lists to CSV in C# is particularly useful for applications that deal with:

  • Data reporting.
  • Data interchange between systems.
  • Archiving structured information.

C# List to CSV File Tutorial

To convert a list to a CSV file in C#, we will:

  • Create a sample list of objects.
  • Use StringBuilder to generate CSV content.
  • Write the CSV content to a file.

Here is the step-by-step implementation:

Step 1: Define a Sample Data Model

public class Person
{
    public string Name { getset; }
    public int Age { getset; }
    public string Email { getset; }
}

Step 2: Create a List of Objects

List<Person> people = new List<Person>
{
    new Person { Name = "Nikunj Satasiya", Age = 30, Email = "nikunj.satasiya@example.com" },
    new Person { Name = "Mansi Satasiya", Age = 29, Email = "mansi.satasyia@example.com" },
    new Person { Name = "Hiren Dobariya", Age = 31, Email = "hiren.dobariya@example.com" }
};

Step 3: Convert the List to CSV Format

using System.Text;
using System.Linq;
 
public string ConvertListToCsv<T>(List<Tlist)
{
    var csvBuilder = new StringBuilder();
    var properties = typeof(T).GetProperties();
 
    // Add header
    csvBuilder.AppendLine(string.Join(","properties.Select(p => p.Name)));
 
    // Add rows
    foreach (var item in list)
    {
        var row = properties.Select(p => p.GetValue(itemnull)?.ToString() ?? "").ToArray();
        csvBuilder.AppendLine(string.Join(","row));
    }
 
    return csvBuilder.ToString();
}

Step 4: Save the CSV Content to a File

string csvContent = ConvertListToCsv(people);
System.IO.File.WriteAllText("people.csv"csvContent);
Console.WriteLine("CSV file created successfully.");

Export List to CSV in C#: Best Practices

  • Handle Special Characters: Ensure that fields containing commas or quotes are properly escaped by enclosing them in quotes.
  • Validate Data: Check for null or invalid values before writing to CSV.
  • Use a Library: For complex CSV files, consider using libraries like CsvHelper.

How to Convert a List to CSV Using C#

If you prefer using a third-party library, here’s how to do it with CsvHelper:

Step 1: Install CsvHelper

Run the following command in your NuGet Package Manager Console:

Install - Package CsvHelper

Step 2: Write the CSV File

using CsvHelper;
using System.Globalization;
using System.IO;
 
using (var writer = new StreamWriter("people.csv"))
using (var csv = new CsvWriter(writerCultureInfo.InvariantCulture))
{
    csv.WriteRecords(people);
}
 
Console.WriteLine("CSV file created successfully using CsvHelper.");

C# Generate CSV from List

This example showcases how to generate a CSV string from a list for scenarios where you don’t need to save the file but want to use the CSV data programmatically:

string csvContent = ConvertListToCsv(people);
Console.WriteLine(csvContent);

Simple C# List to CSV Conversion

For smaller projects, a straightforward approach without additional libraries may be sufficient. The StringBuilder method we used earlier is lightweight and efficient for such cases.

C# Convert IEnumerable to CSV

If you’re working with IEnumerable<T> instead of a List<T>, the same logic applies. Simply replace the method parameter type:

public string ConvertIEnumerableToCsv<T>(IEnumerable<Tenumerable)
{
    var csvBuilder = new StringBuilder();
    var properties = typeof(T).GetProperties();
 
    // Add header
    csvBuilder.AppendLine(string.Join(","properties.Select(p => p.Name)));
 
    // Add rows
    foreach (var item in enumerable)
    {
        var row = properties.Select(p => p.GetValue(itemnull)?.ToString() ?? "").ToArray();
        csvBuilder.AppendLine(string.Join(","row));
    }
 
    return csvBuilder.ToString();
}

Export List to CSV File C# Step-by-Step

To summarize, converting a list to a CSV file in C# involves:

  1. Creating a data model and populating the list.
  2. Formatting the data as CSV using StringBuilder or CsvHelper.
  3. Writing the CSV content to a file.

By following these steps, you can efficiently export data to CSV files in C#.

Conclusion

Whether you’re creating reports, exporting data, or sharing structured information, converting a list to a CSV file in C# is a valuable skill. This article covered various approaches, from manual methods using StringBuilder to advanced techniques with CsvHelper. Implement these techniques to suit your project needs.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

If you have any questions, contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon