Beginner’s Guide to Creating and Writing CSV Files in C# on the .NET Platform

RSDevX
5 min readSep 24, 2024

--

In this tutorial, we will explore how to create a CSV (Comma-Separated Values) text file using C# on the .NET platform, specifically designed for beginners. We will guide you through the entire process, including how to set up the CSV file, write the headers, and input data into it.

Original article on creating CSV text files using C# along with full source code can be found here

A CSV file is a straightforward format for organizing data in a tabular structure using plain text. Each line in the file represents a distinct record, with values separated by commas. The first line typically serves as the header, which describes the columns of the data. For example, instead of “Name,” “Age,” and “City,” we might use “ProductID,” “ProductName,” and “Price.” Subsequent lines will contain the relevant information for each entry, such as a unique identifier for the product, its name, and its price.

CSV files are widely used due to their simplicity; they are easy to read and can be opened with any text editor or spreadsheet application, making them a versatile choice for data storage and exchange. By the end of this tutorial, you will have the skills to create and manage your own CSV files effectively using C#

How to Create and Write a CSV Text File Using C# and StreamWriter

How to Create and Write a CSV Text File Using C# and StreamWriter

Since a CSV file is fundamentally a text file, we can utilize the StreamWriter class from the C# base library to create it. The StreamWriter class, located in the System.IO namespace, is designed for writing text to a stream, such as a file. It is especially useful for generating and managing text files. Below is a code snippet that demonstrates how to create a basic text file using methods from the StreamWriter class

try
{
// Using StreamWriter to create and write to a file
using (StreamWriter fwriter = new StreamWriter("CSVFileName.csv", true)) //true opens the file in append mode
{
fwriter.WriteLine("Text to be written to the file "); // write the header text to file
}
}

full code for C# CSV file creation can be found here

In this code snippet,

we use the StreamWriter class to create and write to a CSV file named “CSVFileName.csv.” The using statement ensures that the StreamWriter is properly disposed of after its operations, which helps manage system resources effectively. The true parameter passed to the StreamWriter constructor opens the file in append mode, allowing us to add new content without overwriting any existing data. Within the block, we use the WriteLine method to write a specific string, “Text to be written to the file,” to the file.

Creating the Headers for the CSV file

Every CSV file features a header that defines and describes its columns, providing essential context for the data that follows. The values in the header are separated by a designated delimiter, which is typically a comma.

string[] CSVHeaderTextArray = { "No", "Name", "Age", "Address" }; //CSV header data

In our code, the array CSVHeaderTextArray is utilized to store these header values, which in this example include “No,” “Name,” “Age,” and “Address.” This array can be easily modified to fit your specific requirements, allowing you to add more headers or remove some as needed, depending on the data you wish to organize.

The next step involves using the string.Join() method to concatenate the header values into a single string, with each value separated by the specified delimiter.

string CSVHeaderText = string.Join(SeperatorCharacter, CSVHeaderTextArray);

For instance, using our delimiter (a comma), the method combines the elements of CSVHeaderTextArray to produce the string CSVHeaderText, which would appear as “No,Name,Age,Address.” This format is crucial for CSV files, as it ensures that the data is correctly interpreted by programs that read the file, such as spreadsheet applications or data processing tools. The resulting CSVHeaderText serves as the first line of our CSV file, establishing a clear structure for the data entries that will follow.

Writing the data to file in CSV format using C#

All data is stored in 2D array called CSVDataArray as shown below.

//CSV data to be stored
string[,] CSVDataArray = {
{ "1", "Alice", "30", "123 Main St, New York" },
{ "2", "Bob", "25", "456 Elm St, Los Angeles" },
{ "3", "Charlie", "35", "789 Oak St, Chicago" },
{ "4", "David", "40", "321 Pine St, Houston" },
{ "5", "Eve", "28", "654 Maple St, Seattle" }
};

we utilize the StreamWriter class to create or open the CSV file specified by CSVFileName, with the true parameter indicating that the file should be opened in append mode. This means that if the file already exists, new data will be added to the end without overwriting any existing content.

using (StreamWriter fwriter = new StreamWriter(CSVFileName, true)) 

Following this, we enter a loop that iterates through the rows of the CSVDataArray. For each row, a StringBuilder object is created to efficiently construct a line of data. Within the inner loop, we append each element of the current row to the StringBuilder, followed by the specified separator character. This process continues until all elements in the row have been processed.

for (int i = 0; i < CSVDataArray.GetLength(0); i++)
{
StringBuilder sb = new StringBuilder();
for (int j = 0; j < CSVDataArray.GetLength(1); j++)
{

sb.Append(CSVDataArray[i, j]);
sb.Append(SeperatorCharacter);
}
sb.Length--; //remove the trailing comma
fwriter.WriteLine(sb.ToString()); //Write data to file

Following this, we enter a loop that iterates through the rows of the CSVDataArray. For each row, a StringBuilder object is created to efficiently construct a line of data. Within the inner loop, we append each element of the current row to the StringBuilder, followed by the specified separator character. This process continues until all elements in the row have been processed.

After constructing the full string representation of the row, we remove the trailing comma by adjusting the Length property of the StringBuilder. Finally, we write the completed string to the file using WriteLine. This method is called for each row of data, resulting in a well-structured CSV file that contains both the header and the corresponding data entries. The use of StringBuilder optimizes string concatenation, making the code more efficient, especially when handling larger datasets.

--

--