Building a Simple CSV Parser in C#
By FoxLearn 1/16/2025 3:31:05 AM 30
In this guide, we’ll walk through how to create a basic CSV parser in C# that reads CSV files and returns the data in a list format.
This parser will be straightforward and perfect for basic CSV files, although more complex files (e.g., those with embedded commas in the data) may require an advanced parser.
How to Build a Simple CSV Parser in C#
First, you’ll need to create a new C# application in Visual Studio. Once your project is set up, you’ll need to decide where to build and call your parser function. For simplicity, you can start by placing the function inside the Form1.cs
file under the public Form1()
definition.
Next, ensure that the necessary namespaces are included at the top of your code file. Specifically, you'll need to add using System.IO;
as it is not included by default in a new project.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; // Make sure to add this
Building the CSV Parser Function
The first step in creating the parser is declaring the function that will read the CSV file. The function will accept a file path as input and return a list of string arrays, where each array corresponds to a row in the CSV file.
public List<string[]> parseCSV(string path) { }
The reason we use a List<string[]>
rather than a string[][]
is that lists are more flexible and allow for dynamic addition and removal of elements, unlike arrays.
Inside the function, declare a list to hold the parsed data:
List<string[]> parsedData = new List<string[]>();
We will use the StreamReader
class from the System.IO
namespace to read the CSV file line by line. This approach is efficient as it allows you to process each line as it’s read, instead of loading the entire file into memory at once.
To ensure proper resource management, we’ll wrap the StreamReader
in a using
statement, which ensures that the reader is disposed of automatically when it goes out of scope.
using (StreamReader readFile = new StreamReader(path)) { }
Within the using
block, we need two variables: one for the current line and another for holding the individual values of that line (split by commas).
string line; string[] row;
Now, we’ll read the file line by line and split each line into an array of strings. We can use the Split
method to break the line at each comma.
while ((line = readFile.ReadLine()) != null) { row = line.Split(','); parsedData.Add(row); }
The while
loop continues reading until it encounters an empty line (null). Inside the loop, the Split(',')
method breaks each line into an array of strings, with each string representing a column in that row. After splitting the line, we add the array to the parsedData
list.
It’s essential to handle potential errors that might occur when reading the file. For this, we’ll enclose the reading logic in a try-catch
block. If an exception occurs, we can catch it and display the error message to the user.
public List<string[]> parseCSV(string path) { List<string[]> parsedData = new List<string[]>(); try { using (StreamReader readFile = new StreamReader(path)) { string line; string[] row; while ((line = readFile.ReadLine()) != null) { row = line.Split(','); parsedData.Add(row); } } } catch (Exception e) { MessageBox.Show(e.Message); } return parsedData; }
In the case of an error, such as an invalid file path or unreadable content, the exception message will be shown in a message box, and an empty list will be returned.
How the Parser Works
The parseCSV
function reads the specified file line by line, splits each line at commas, and stores the resulting arrays in a list. This makes it easy to manipulate and display the data later on, whether in a DataTable
, GridView
, or some other structure.
Moreover, you can easily modify this parser to work with other delimited files by changing the delimiter in the Split
method. For example, to parse tab-separated values (TSV), you would replace line.Split(',')
with line.Split('\t')
.
This simple CSV parser is an excellent tool for reading and processing basic CSV files in C#. With just a few lines of code, you can quickly load CSV data into a list and use it however you like.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#