In few previous manufactures, I have explained how we tin read JSON data in C# and how to read excel file in C#, now in this article, I have provided code sample using panel application to show how to read a text file in C# line past line or reading unabridged text file equally a string in one past go using C#.

Let'due south a wait at each of the example code, one in which text file is read and converted into string, i.eastward, using System.IO.ReadAllText() and another is reading text file line by line using System.IO.ReadAllLines() which returns array of line, and we can loop that assortment to print each line of text file.

Read File in .NET Framework 4.five Console awarding

Reading file in C# line by line

In this example, we will read a text file line by line using System.IO.ReadALLLines() in panel awarding.

And so, if you are new to C# or Visual Studio, you tin create a new Console application past opening Visual Studio, navigating to "New"-> "Project" -> Select "Windows Classic" from left-pane and "Console app (Windows Application)"-> Requite a proper name to your projection "ReadInCSharp" and click "OK"

read-text-file-in-csharp-min.png

Now, inside Plan.cs, we volition write our lawmaking

          using System; using System.IO;  namespace ReadInCSharp {     form Programme     {         static void Main(string[] args)         {             //file in disk             var FileUrl = @"D:\testFile.txt";              //file lines             string[] lines = File.ReadAllLines(FileUrl);              //loop through each file line             foreach (cord line in lines)             {                 Console.WriteLine(line);             }          }     } }                  

Output:

          This is test file. To Read text file in C# Sample.        

C-sharp-read-file-line-by-line-min.png

In the above, code we are using foreach loop to read all lines of an string array.

Reading text in C# all line at in one case

Permit'southward accept a look at C# lawmaking to read all lines at one time of a text file.

          using Organization; using Organization.IO;  namespace ReadInCSharp {     class Program     {         static void Principal(cord[] args)         {             //file in disk             var FileUrl = @"D:\testFile.txt";              // Read entire text file content in one string               string text = File.ReadAllText(FileUrl);             Console.WriteLine(text);           }     } }                  

Output:

          This is test file. To Read text file in C# Sample.        

read-all-lines-c-sharp-min.png

Reading Text file using StreamReader

There is one more way to read lines of a text file in C#, which is using StreamReader.

StreamReader class implements a TextReader that reads characters from a byte stream in a item encoding.

          using Organization; using System.IO;  namespace ReadInCSharp {     class Programme     {         static void Main(cord[] args)         {             //file in deejay             var FileUrl = @"D:\testFile.txt";              try             {                 // Create an instance of StreamReader to read from a file.                 // The using statement also closes the StreamReader.                 using (StreamReader sr = new StreamReader(FileUrl))                 {                     string line;                    //read the line past line and print each line                     while ((line = sr.ReadLine()) != null)                     {                         Console.WriteLine(line);                     }                 }             }             catch (Exception e)             {                 // Something went wrong.                 Console.WriteLine("The file could not be read:");                 //impress error bulletin                 Console.WriteLine(east.Bulletin);             }           }     } }                  

Output is same as above, in the abovde code, we are using StreamReader instance to read text from file.

streamreader-read-text-file-csharp-min.png

As you can see in the higher up code, we are feeding the File url to "StreamReader" class object then we are reading file line by line using sr.ReadLine(), which gives the states ane line at a fourth dimension from text file, then using Console.WriteLine(), we are printing the value of that line console application.

Read File in .NET Cadre Console application

In the higher up instance, we were reading file using .NET framework, but you can also read files using 'StreamReader' in .Cyberspace Cadre, here is the working example.

Before, I show yous instance, I accept created a new console application using .NET Core in Visual Studio 2019 (Open up Visual Studio -> Click on Create new project -> Select "Panel App (.Internet Core)" from templates -> Click "Side by side", give your project a name "ReadFileInNetCore" -> Click "Create")

read-text-file-net-core-min.png

Considering you have text file at location "D:\testFile.txt", you can utilise the below C# Code in .NET Core to read text file line by line.

          using Organisation; using System.IO;  namespace ReadFileInNetCore {     class Program     {         static void Main(string[] args)         {             FileStream fileStream = new FileStream(@"D:\testFile.txt", FileMode.Open);             //read file line by line using StreamReader             using (StreamReader reader = new StreamReader(fileStream))             {                 string line = "";                 while ((line = reader.ReadLine()) != null)                 {                     //print line                     Console.WriteLine(line);                 }                                 }             Console.WriteLine("Press any key to go on");             Console.ReadKey();         }     } }                  

If you volition run across the above lawmaking, you will find, at that place isn't any divergence in C# Code, when working with .NET four.5 or .NET Cadre.

Output:

read-file-line-by-line-net-core-min.png

To read all files at one time, you tin can apply "ReadAllText" as mentioned for .Internet Framework "Organisation.IO.File.ReadAllText("YourFileLocatio.txt");"

Note: If you are working with .NET Core three and working with web-application, and you want to read file from wwwroot location, you lot can locate "wwwroot" folder equally below:

                      private readonly IWebHostEnvironment _webHostEnvironment;      public YourController (IWebHostEnvironment webHostEnvironment)     {         _webHostEnvironment= webHostEnvironment;     }      public IActionResult Index()     {         cord webRootPath = _webHostEnvironment.WebRootPath;         string contentRootPath = _webHostEnvironment.ContentRootPath;          string path ="";         path = Path.Combine(webRootPath , "yourFolder");         //or path = Path.Combine(contentRootPath , "wwwroot" ,"yourFolder" );         render View();     }        

Y'all may also like to read:

Read PDF file in C# using iTextSharp