To write a list of objects to a CSV file manually (without using a third-party library like CsvHelper), you can use
System.IO.StreamWriter and reflection or direct property access.
Example: Write a List of Objects to CSV
Model:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Writing to CSV:
using System;
using System.Collections.Generic;
using System.IO;
public class CsvWriterExample
{
public static void WriteCsv(string path, List<Person> people)
{
using (var writer = new StreamWriter(path))
{
// Write header
writer.WriteLine("Id,Name,Email");
foreach (var person in people)
{
// Escape commas and quotes if necessary
string line = $"{Escape(person.Id.ToString())},{Escape(person.Name)},{Escape(person.Email)}";
writer.WriteLine(line);
}
}
}
private static string Escape(string field)
{
if (field.Contains(",") || field.Contains("\"") || field.Contains("\n"))
{
// Escape quotes and wrap in quotes
field = field.Replace("\"", "\"\"");
return $"\"{field}\"";
}
return field;
}
}
Usage:
var people = new List<Person>
{
new Person { Id = 1, Name = "John", Email = "john@example.com" },
new Person { Id = 2, Name = "Jane, A.", Email = "jane@example.com" }, // comma in name
};
CsvWriterExample.WriteCsv("people.csv", people);
Why Use Escape()?
CSV fields must be quoted if they contain:
Commas ,
Newlines \n
Double quotes "
Double quotes in a field must be escaped as "" and the entire field wrapped in quotes.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To write a list of objects to a CSV file manually (without using a third-party library like CsvHelper), you can use
System.IO.StreamWriterandreflectionor direct property access.Example: Write a List of Objects to CSV
Model:
Writing to CSV:
Usage:
Why Use
Escape()?,\n"""and the entire field wrapped in quotes.