Date:

Share:

C# | Read Delimited Text File

Related Articles

In this article, I will show you how to read a separated text file in c #. To read the text file I will use the TextReader class to read a continuous series of characters as well as texts from a text file, this class is in the namespace or directory of System.IO. Here, he will also explain how to read a text file and convert it to a DataTable using the c # with an example.

You can also read my article on reading and writing text files in ASP.NET using C #

Recently, in one of my projects, I got the requirement to read the data from the separated text file and convert it to DataTable. On the Internet, I found many different ways to store this requirement, but I created a very easy and better way to read the separated file in c #. Let’s create a sample app for reading text files and converting them to DataTable using C # so you can get more ideas about it.

In my previous articles I explained,

  1. Calculate the sum of the DataTable column
  2. C # | Given data to CSV
  3. Export all Excel sheets to DataSet in C # and VB.NET
  4. Get separate records from Datatable using LINQ C #
  5. Read a CSV file in ASP.NET with example C # and VB.NET
  6. Export data set / data to CSV file using C # and VB.NET

That you might want to read.

Let’s start our application step by step.

Level 1: Open Visual Studio.

level2: Create a new project (for example, I created a console application in .Net core 5.0)

Search and select a terminal application >> Click Next.

Create a new project

Step 3: Now, you need to set up the project.

Provide your project name >> Choose a location for your project >> Click Next.

Set up a new project

Step 4: In the next window, you need to select your targeted frame. (I chose 5.0)

Step 5: You can see that the project was created successfully, now you need to create one separate text file and insert it into the directory of folders as shown below.

Create a separated text file

In the text file created I wrote the separated records in the following sample tube.

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 directory.

using System.Data;
using System.IO;

Step 7: Now, in the same class, I have created one function with parameters that returns DataTable.

public static DataTable ReadFile(string FilePathchar delimiterbool 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 created a function with parameters that gets a string of different FilePath parameters for the path of a separated text file, a character separator for the separator contained the text file and a boolean parameter isFirstRowHeader to identify whether the first line of the text file contains title information or not.

I then created a new object for DataTable. Next, I opened the text file using the TextReader class, and using a while loop I read the entire file. Whenever there is a row, I split that whole row and store each piece of data in an array of strings called arrItems.

For the title, I identified the title based on the boolean flag isFirstRowHeader, if that flag is correct, it means we should consider the first line of text file as the title, and the DataTable column name should be according to the name available in the first line of the text file. If the flag isFirstRowHeader is false then the column name will create something like column 1, column 2 column 3 etc. based on counting the total items available in the first line of the text file.

Finally, for all the other records, I entered into the DataTable using DataRow and returned the prepared DataTable as a result / response / output of a function created called ReadFile.

Step 8: Call the created function ReadFile into the main method.

static void Main(string[] args)
        {
            //Fatch File Path
            string path = @"F:CodingvilaCodingvila_ReadDelimitedFileFilesData.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("rn");
            }
            Console.ReadKey();
        }

explanation:

As you can see in the code above, here I called the function that was created ReadFile and stored the result / response / output of this specific function in Datatable.

Now, you can manipulate all the records available in the data table 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 used the statement Console.ReadKey (); At the end of the function. This statement usually waits for user input. In fact, if you do not write this statement your result / output window will not be saved on the screen.

Productivity

outcome

Summary

In this article we learned how to read text files as well as a way to prepare a DataTable by reading a text file in C #.

.

Source

Popular Articles