In few previous articles, I have explained how we can read JSON data in C# and how to read excel file in C#, now in this article, I take provided code sample using panel application to bear witness how to read a text file in C# line by line or reading unabridged text file as a string in 1 by go using C#.

Allow's a expect at each of the example lawmaking, i in which text file is read and converted into string, i.eastward, using Organization.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 array to print each line of text file.

Read File in .Internet Framework 4.v Console application

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

So, if you are new to C# or Visual Studio, yous can create a new Panel application by opening Visual Studio, navigating to "New"-> "Project" -> Select "Windows Archetype" from left-pane and "Console app (Windows Awarding)"-> Requite a proper noun to your project "ReadInCSharp" and click "OK"

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

At present, inside Programme.cs, we volition write our code

          using System; using System.IO;  namespace ReadInCSharp {     class Plan     {         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 (string 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

Allow'southward accept a look at C# code to read all lines at once of a text file.

          using System; using System.IO;  namespace ReadInCSharp {     form Program     {         static void Main(string[] 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 1 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 Arrangement; using Arrangement.IO;  namespace ReadInCSharp {     class Plan     {         static void Main(string[] args)         {             //file in disk             var FileUrl = @"D:\testFile.txt";              try             {                 // Create an instance of StreamReader to read from a file.                 // The using statement besides 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 eastward)             {                 // Something went incorrect.                 Console.WriteLine("The file could not be read:");                 //print error bulletin                 Panel.WriteLine(e.Message);             }           }     } }                  

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

Equally you tin encounter in the above code, nosotros are feeding the File url to "StreamReader" class object and then we are reading file line by line using sr.ReadLine(), which gives us 1 line at a time from text file, then using Panel.WriteLine(), we are press the value of that line console application.

Read File in .NET Core Console application

In the higher up case, nosotros were reading file using .NET framework, but you tin can also read files using 'StreamReader' in .NET Core, here is the working example.

Before, I show you lot example, I have created a new console application using .Internet Core in Visual Studio 2019 (Open Visual Studio -> Click on Create new project -> Select "Console App (.Cyberspace Core)" from templates -> Click "Adjacent", requite your project a proper name "ReadFileInNetCore" -> Click "Create")

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

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

          using Organisation; using Arrangement.IO;  namespace ReadFileInNetCore {     class Programme     {         static void Main(string[] args)         {             FileStream fileStream = new FileStream(@"D:\testFile.txt", FileMode.Open up);             //read file line by line using StreamReader             using (StreamReader reader = new StreamReader(fileStream))             {                 cord line = "";                 while ((line = reader.ReadLine()) != null)                 {                     //print line                     Console.WriteLine(line);                 }                                 }             Console.WriteLine("Press whatever primal to go along");             Panel.ReadKey();         }     } }                  

If you will meet the in a higher place code, yous volition notice, there isn't any divergence 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, you can use "ReadAllText" every bit mentioned for .NET Framework "System.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 as below:

                      private readonly IWebHostEnvironment _webHostEnvironment;      public YourController (IWebHostEnvironment webHostEnvironment)     {         _webHostEnvironment= webHostEnvironment;     }      public IActionResult Alphabetize()     {         string webRootPath = _webHostEnvironment.WebRootPath;         cord 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