Working with CSV files is one of the most common tasks in software development, especially when dealing with data export, reporting, or integration with other systems. In this guide, you will learn how to write data into CSV file in C# with step-by-step explanations, real-world examples, and practical use cases.
CSV (Comma-Separated Values) is a simple text file format used to store tabular data. Each line represents a record, and values within a record are separated by commas. CSV files are widely used because they are lightweight and compatible with most software including Excel, Google Sheets, and databases.
Before we dive into coding, let’s understand the core concepts:
Data can be stored in arrays, lists, or objects. Each record can be written as a line in the CSV file.
Here’s a simple example of writing data into a CSV file using C#:
using System; using System.IO; using System.Collections.Generic; class Program { static void Main() { string filePath = "data.csv"; // Sample data to write var data = new List<string[]>() { new string[] { "Name", "Age", "Email" }, new string[] { "Alice", "30", "alice@example.com" }, new string[] { "Bob", "25", "bob@example.com" }, new string[] { "Charlie", "35", "charlie@example.com" } }; using (StreamWriter writer = new StreamWriter(filePath)) { foreach (var row in data) { writer.WriteLine(string.Join(",", row)); } } Console.WriteLine("CSV file created successfully!"); } }
Suppose you have a list of employees and want to export it to a CSV file:
class Employee { public string Name { get; set; } public int Age { get; set; } public string Department { get; set; } } var employees = new List<Employee>() { new Employee() { Name = "Alice", Age = 30, Department = "HR" }, new Employee() { Name = "Bob", Age = 25, Department = "IT" }, new Employee() { Name = "Charlie", Age = 35, Department = "Finance" } }; using (StreamWriter writer = new StreamWriter("employees.csv")) { writer.WriteLine("Name,Age,Department"); foreach (var emp in employees) { writer.WriteLine($"{emp.Name},{emp.Age},{emp.Department}"); } } Console.WriteLine("Employee CSV file exported successfully!");
| Method | Pros | Cons |
|---|---|---|
| Manual StreamWriter | Simple, no external library needed | Requires careful handling of commas, quotes, and large data |
| CSV Libraries (e.g., CsvHelper) | Handles escaping, mapping, and large files easily | Extra dependency, slight learning curve |
Writing data into CSV file in C# is a fundamental skill for developers working with data export, reporting, or system integrations. Whether you use basic
StreamWriter or advanced CSV libraries, understanding the core concepts, formatting rules, and best practices ensures reliable and maintainable CSV handling in your applications.
No, CSV is a text format, so case sensitivity depends on how the application reading it interprets the data. For instance, Excel treats headers as case-insensitive.
Copyrights © 2024 letsupdateskills All rights reserved