In this article, I'll show you how to read a delimited text file in c#. To read the text file I'll use TextReader class to read a sequential series of characters as well as texts from a text file, this class is found in the System.IO namespace or library. Here, will also explain how to read a text file and convert it into DataTable using the c# with example.
You can also read my article about Read And Write Text Files In ASP.NET using C#
Recently, in one of my projects, I got the requirement for reading the data from the delimited text file and converting it into DataTable. On the internet, I found many different ways to archive this requirement but I created a very easy and optimized way to read the delimited file in c#. Let's create a sample application for reading text files and converting them into DataTable using C# so you can get more ideas about it.
In my previous articles, I explained,
- Calculate The SUM of the DataTable Column
- C# | Datatable to CSV
- Export All The Excel Sheets to DataSet in C# and VB.NET
- Get Distinct Records From Datatable using LINQ C#
- Read CSV File In ASP.NET With Example C# and VB.NET
- Export Dataset/Datatable to CSV File Using C# and VB.NET
That you might like to read.
Let's start our application step by step.
Step 1: Open Visual Studio.
Step 2: Create a new project (for a demonstration I created a console application that is in .Net core 5.0)
Search and Select Console Application >> Click Next.
Step 3: Now, you have to configure the project.
Provide the name of your project >> Select location for your project >> Click Next.
Step 4: In the next window, you have to select your targeted framework. (I selected framework 5.0)
Step 5: You can see the project is created successfully, now you need to create one delimited text file and put it into the folder directory as shown below.
In the created text file I wrote the following sample pipe separated records.
Id|Type|Title|Author|Date 1101|article|Angular 12 CRUD Operation|Nikunj Satasiya|01-01-2022 1102|Blog|Google Cloud Platform For Student|Nikunj Satasiya|02-01-2022 1103|article|Best Programming Articles for Software Development|Nikunj Satasiya|08-01-2022 1104|Blog|How to Export PDF from HTML in Angular 12|Nikunj Satasiya|09-01-2022 1105|article|Angular PowerShell ng.ps1 Can Not be Loaded and Not Digitally signed|Nikunj Satasiya|10-01-2022 1106|article|Why Do Students Need Online Python Programming Help?|Nikunj Satasiya|11-01-2022 1107|Blog|Angular 12 Bar Chart Using ng2-Charts|Nikunj Satasiya|12-01-2022 1108|Blog|Rename Column Only If Exists in PostgreSQL|Nikunj Satasiya|15-01-2022 1109|article|Create REST API with ASP.NET Core 5.0 And Entity Framework Core|Nikunj Satasiya|20-01-2022
Step 6: Open, the program.cs file and import the following namespace library.
using System.Data; using System.IO;
Step 7: Now, in the same class, I have created one parameterized function that returns DataTable.
public static DataTable ReadFile(string FilePath, char delimiter, bool isFirstRowHeader = true) { try { //Create object of Datatable DataTable objDt = new DataTable(); //Open and Read Delimited Text File using (TextReader tr = File.OpenText(FilePath)) { string line; //Read all lines from file while ((line = tr.ReadLine()) != null) { //split data based on delimiter/separator and convert it into string array string[] arrItems = line.Split(delimiter); //Check for first row of file if (objDt.Columns.Count == 0) { // If first row of text file is header then, we will not put that data into datarow and consider as column name if (isFirstRowHeader) { for (int i = 0; i < arrItems.Length; i++) objDt.Columns.Add(new DataColumn(Convert.ToString(arrItems[i]), typeof(string))); continue; } else { // Create the data columns for the data table based on the number of items on the first line of the file for (int i = 0; i < arrItems.Length; i++) objDt.Columns.Add(new DataColumn("Column" + Convert.ToString(i), typeof(string))); } } //Insert data from text file to datarow objDt.Rows.Add(arrItems); } } //return datatable return objDt; } catch (Exception) { throw; } }
Explanation:
As you can see in the code above, here I have created a parameterized function that accepts 3 different paramiters string FilePath for the path of delimited text file, character delimiter for the delimiter contained the text file as well as Boolean parameter isFirstRowHeader for identifying whether the first row of the text file is contained header information or not.
Then I have created a new object objDt for DataTable. After that, I opened the text file using TextReader class, and using the while loop I read the whole file. Every time any row is found, I split that entire row and store each piece of data into a string array called arrItems.
For the header, I identified the header based on the boolean flag isFirstRowHeader, if this flag is true, means we need to consider 1st row of a text file as header, and the column name of DataTable should be as per the name available in the first row of the text file. If the flag isFirstRowHeader is false then the column name will be generated something like column1, column2 column 3 and etc. based on the count of total items available in the first row of the text file.
Finally, for all other records, I inserted into DataTable using the DataRow and returned the prepared DataTable as a Result/Response/Output of created function called ReadFile.
Step 8: Call Created Function ReadFile into Main Method.
static void Main(string[] args) { //Fatch File Path string path = @"F:\Codingvila\Codingvila_ReadDelimitedFile\Files\Data.txt"; //Call Readfile method and pass required parameters DataTable dtTable = ReadFile(FilePath: path, delimiter: '|', isFirstRowHeader: true); // Print Data of Datatable foreach (DataRow dataRow in dtTable.Rows) { foreach (var item in dataRow.ItemArray) { Console.WriteLine(item); } Console.WriteLine("\r\n"); } Console.ReadKey(); }
Explanation:
As you can see in the code above, here I have called the created function ReadFile and stored the Result/Response/Output of this particular function into Datatable.
Now, you can manipulate all the records available in the Datatable based on your needs or requirement. Here, for demonstration purposes, I printed the records using for each loop.
Note: If you noticed then here, I have used statement Console.ReadKey(); at the end of the function. This statement generally waits for user input. Actually, if you do not write this statement your result/output window will not preserve on the screen.
Output
Summary
In this article, we learned, how to read text files as well as a way to prepare DataTable by reading a text file in C#.