Learn to Create a CSV Text File Using C# on .NET for Storing Data in Comma Delimited Format

by xanthium-enterprises in Circuits > Software

34 Views, 0 Favorites, 0 Comments

Learn to Create a CSV Text File Using C# on .NET for Storing Data in Comma Delimited Format

Learn to Create (Comma Separated Values) CSV files using C# on .NET platform and Write Data to it

In this Instructable guide,

we will explore how to create a CSV (Comma-Separated Values) text file using C# (Csharp) on the .NET platform and store data within it. Aimed at beginners, this tutorial will walk you through the steps of creating a CSV file, writing titles to the file, and populating it with data using C#

You can find the original article along with full source code using the below link.

  1. An Introductory Guide to Creating, Reading, and Writing Data in CSV Files with C# for beginners


Supplies

visual-basic-serial-programming-visual-studio.jpg
image_19.png

For this tutorial ,you may need to download some software's to compile and run the programs presented here.

For building our program we will be using the Visual Studio Community Edition that can be freely downloaded from the Microsoft website.

You can also use Microsoft .NET SDK CLI, if you are on Linux or requires a light weight option on Windows.

If you are new to Microsoft .NET SDK CLI ,you can check out our tutorials on

How to Compile and Develop Programs using Microsoft .NET SDK CLI here

If you prefer a Video Tutorial ,Check our Video on using Microsoft .NET SDK CLI

What Is a CSV Text File

image_67.png


A CSV (Comma-Separated Values) text file is a simple format used to store and organize data in a tabular structure, where each line represents a row of data and values within that row are separated by commas, representing columns.

The first line typically contains titles that describe each column (e.g., "Product," "Quantity," "Price"). Stored as plain text, CSV files are easily created and edited with any text editor, making them highly accessible. Their human-readable nature allows for easy data sharing, and they are compatible with various applications, including spreadsheet software and databases.

CSV files are commonly used for transferring data between applications, such as importing and exporting data to and from databases and spreadsheets, as well as for simple data storage, such as contact lists or inventory records. Overall, CSV files provide a straightforward and effective way to store and exchange structured data

Creating a Comma Sepearted Values Text File Using C#

image_63.png

Since a CSV file is essentially a text file, we can use the StreamWriter class from the C# base library to create it.

StreamWriter is a class designed for writing text to a stream, such as a file, and is part of the System.IO namespace. It is particularly effective for creating and managing text files.

The code below demonstrates how to create a simple text file using the methods of the StreamWriter class. We will later modify this code to generate a CSV file

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
{
writer.WriteLine("Text to be written to the file "); // write the header text to file
}
}
catch (Exception Ex)
{
}

On running this code ,a text file is create on the disk with the name CSVFileName.CSV and some text is written into it 

Creating the Header for Your CSV File Using C#

The SeparatorCharacter variable is used to specify the delimiter, such as a comma, colon, semicolon, or pipe symbol (|). By modifying this variable, you can create a comma-delimited file, a colon-delimited file, or a tab-delimited file, depending on your needs

All CSV files include a header that defines and describes the columns. The header values are separated by the specified delimiter, as mentioned earlier.

In this context, the CSVHeaderTextArray is used to store the header data. You can modify the header by adding or removing entries based on your requirements.


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


Next, we use the string.Join() method to combine the header values using the specified delimiter. For example, this will format the header as No, Name, Age, Address within the CSVHeaderText string.

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

Writing the Data in CSV Format Into the Text File Using C#

All the data we need to write to our file is stored inside the 2 dimensional array CSVDataArray in No, Name, Age, Address format, this is done for convenience

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" }
};

Now, we will write data from the array to a CSV text file in a comma-delimited format using C#. The first step is to create the CSV text file on the disk, using the name stored in the string variable CSVFileName. To accomplish this, we will utilize the StreamWriter class, which allows us to create a file with a specific name on the hard drive.

using (StreamWriter fwriter = new StreamWriter(CSVFileName, true)) //true opens the file in append mode

Once the file is created, we will write the header to our CSV file. After that, we will begin appending data from the 2D array CSVDataArray to the CSV text file. This process will ensure that all the data is organized correctly, maintaining the specified structure of the CSV format.

using (StreamWriter fwriter = new StreamWriter(CSVFileName, true)) //true opens the file in append mode
{
fwriter.WriteLine(CSVHeaderText); // write the header text to file
// Write
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
//Console.WriteLine(sb.ToString());
}//end of internal for loop
}//end of using


In the above code, we are utilizing two nested for loops to iterate through the data in the 2D array CSVDataArray and append each value to the StringBuilder object, sb, along with the separator character. This approach allows us to efficiently build the CSV format by sequentially adding each element from the array.

Full source code along with tutorial can be found here


Retrieving Data From a CSV File Using C#

image_68.png

In this section, we will utilize the StreamReader class to read the data stored in the CSV file line by line. As we read each line, we can then use the Split() method to divide the line into individual strings based on the specified delimiter. This process allows us to extract each value from the CSV file for further processing


try
{
using (StreamReader CSVReader = new StreamReader(CSVFileName))
{
string line;
while ((line = CSVReader.ReadLine()) != null) //readline by line till u meet the null char
{
Console.WriteLine(line);
string[] individualchar = line.Split(","); //split the line along comma

foreach(string c in individualchar)
{
Console.Write($"{c} ");
}

Console.WriteLine();
}
}
}

Inside the try block, a StreamReader instance named CSVReader is initialized within a using statement, which opens the CSV file specified by the CSVFileName variable. This setup guarantees that the file will be closed properly after reading, even if an error occurs.

The code then enters a while loop that reads the file line by line until it encounters a null value, indicating the end of the file. For each line read, the entire line is printed to the console, providing visibility into the raw data.

The line is subsequently split into individual values using the Split(",") method, creating an array of strings called individualchar, where each element corresponds to a value in the CSV row.

A foreach loop then iterates through this array, printing each value followed by a space, which formats the output neatly on the same line.

Full source code along with tutorial can be found here