C# Read CSV file in .NET Core using TextFieldParser
Today I am going to talk about a new simple approach to read CSV file in .NET Core using TextFieldParser parser.
In our previous article, we already talked about a couple of approaches like TinyParser and CSVHelper to parse CSV files in .NET Core framework-based applications. CSV files are a popular and useful means of persisting the application data.
Today in this article, we will cover below aspects,
What is TextFieldParser
TextFieldParser class has been ported from the namespace Microsoft.VisualBasic.FileIO, which was originally part of Visual Basic.
Please note that this parser is available for .NET Core 3.0 and above only.
It doesn’t support .NET Core 2.2 and lower versions.
The TextFieldParser provides methods and properties for parsing structured text files and supports parsing for two types of files delimited (CSV) and Fixed width files.
Getting Started
Let’s create a .NET Core application.
To keep it simple I have used the .NET Core C# Console application.
I have used the .NET Core 3.1 version.
Using TextFieldParser for CSV parser
TextFieldParser is a very simple and lightweight parser available for CSV Reading and parsing using C#.
This parser is available by default in .NET Core 3.0 and above. You need to add the below namespace to your file and you are all set to use it.
using Microsoft.VisualBasic.FileIO;
It lets you parse CSV and helps you deserialize the data into proper objects too.
Here is CSV file with data. Let’s use this file as an example and perform a reading.
private static string ReadCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
string jsonString = string.Empty;
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields;
bool tableCreated = false;
while (tableCreated == false)
{
colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
tableCreated = true;
}
while (!csvReader.EndOfData)
{
csvData.Rows.Add(csvReader.ReadFields());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "Error:Parsing CSV";
}
//if everything goes well, serialize csv to json
jsonString = JsonConvert.SerializeObject(csvData);
return jsonString;
}
Please see below the client code following namespaces to your code,
Here is the output on the console,
Below is a simple accessor class for UserDetails,
public class UserDetails
{
public string ID { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Other references:
- CSV Parsing in C# using TinyParser and CSVHelper
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Summary
TextFieldParser is an easy and simple parser for reading CSV files using C#. It provides methods, and properties for parsing files like delimited (CSV), and Fixed width files easily. You don’t really need to use any third-party software etc as it comes built into .NET Core 3.0+ as default.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Thank you ,very useful!
Thanks Troy. Glad it helped you !
This looked so handy: no need for reflection, it builds a DataTable with all the right field names.
Unfortunately, it would appear something has changed since you wrote this, or you’ve set serializer options that are not evident, because when I try to serialize an object this way, I get:
Unhandled exception. System.NotSupportedException: The collection type ‘System.Data.DataRelationCollection’ on ‘System.Data.DataTable.ChildRelations’ is not supported.
Thanks Derek for your query. Indeed this is very handy . Based on your comments , I did validate again and for me everything works perfectly fine.
I am using newtonsoft 12.0.1 for serialization and deserialization. Please confim yours.
Please confirm line number where you are getting this exception ? Thanks.
Excellent..made by task easy . Thank you
Glad it helped you. Thanks for the feedback!
It’s good to know that we do not really need to depend on any external package. Thanks for the article.
Thanks Shane for the feedback!