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
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.
Supplies
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
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#
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
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.
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.
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
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.
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.
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#
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
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