In few previous manufactures, I have explained how we tin can 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 by line or reading entire text file equally a string in one by become using C#.

Let's a look at each of the example lawmaking, i in which text file is read and converted into string, i.due east, using System.IO.ReadAllText() and another is reading text file line by line using Organization.IO.ReadAllLines() which returns array of line, and we can loop that array to impress each line of text file.

Read File in .NET Framework iv.v Console application

Reading file in C# line by line

In this example, nosotros will read a text file line by line using System.IO.ReadALLLines() in console application.

So, if y'all are new to C# or Visual Studio, you can create a new Console application by opening Visual Studio, navigating to "New"-> "Projection" -> Select "Windows Classic" from left-pane and "Console app (Windows Application)"-> Give a name to your projection "ReadInCSharp" and click "OK"

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

Now, inside Program.cs, we volition write our code

          using System; using System.IO;  namespace ReadInCSharp {     class Plan     {         static void Principal(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)             {                 Panel.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 assortment.

Reading text in C# all line at once

Let'due south have a look at C# code to read all lines at one time of a text file.

          using Organization; using System.IO;  namespace ReadInCSharp {     course Program     {         static void Principal(string[] args)         {             //file in disk             var FileUrl = @"D:\testFile.txt";              // Read entire text file content in 1 string               string text = File.ReadAllText(FileUrl);             Panel.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

In that location is ane 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 particular encoding.

          using Organisation; using System.IO;  namespace ReadInCSharp {     grade Program     {         static void Principal(string[] args)         {             //file in disk             var FileUrl = @"D:\testFile.txt";              try             {                 // Create an case of StreamReader to read from a file.                 // The using statement as well closes the StreamReader.                 using (StreamReader sr = new StreamReader(FileUrl))                 {                     string line;                    //read the line by line and print each line                     while ((line = sr.ReadLine()) != zero)                     {                         Console.WriteLine(line);                     }                 }             }             grab (Exception e)             {                 // Something went wrong.                 Console.WriteLine("The file could not be read:");                 //print error bulletin                 Console.WriteLine(eastward.Bulletin);             }           }     } }                  

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

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

As you tin can meet in the above lawmaking, nosotros are feeding the File url to "StreamReader" class object and then we are reading file line past line using sr.ReadLine(), which gives united states of america 1 line at a time from text file, then using Console.WriteLine(), we are press the value of that line panel application.

Read File in .NET Core Console application

In the above example, we were reading file using .NET framework, but yous can also read files using 'StreamReader' in .Internet Core, here is the working instance.

Before, I evidence yous example, I accept created a new console application using .NET Cadre in Visual Studio 2019 (Open Visual Studio -> Click on Create new project -> Select "Console App (.Net Cadre)" from templates -> Click "Next", give your projection a proper noun "ReadFileInNetCore" -> Click "Create")

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

Considering you lot take text file at location "D:\testFile.txt", y'all can apply the below C# Lawmaking in .Cyberspace Core to read text file line by line.

          using System; 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                     Panel.WriteLine(line);                 }                                 }             Console.WriteLine("Press any central to keep");             Console.ReadKey();         }     } }                  

If you lot volition run across the above code, y'all will notice, there isn't whatsoever difference in C# Code, when working with .NET four.5 or .NET Core.

Output:

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

To read all files at once, yous tin use "ReadAllText" as mentioned for .Net Framework "System.IO.File.ReadAllText("YourFileLocatio.txt");"

Annotation: If you are working with .NET Cadre iii and working with spider web-application, and you want to read file from wwwroot location, yous tin can locate "wwwroot" folder as below:

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

You may also similar to read:

Read PDF file in C# using iTextSharp