In few previous articles, I have explained how we can read JSON information in C# and how to read excel file in C#, now in this commodity, I take provided lawmaking sample using panel application to show how to read a text file in C# line past line or reading entire text file as a string in one by go using C#.

Let'south a await at each of the example code, one in which text file is read and converted into string, i.e, using Arrangement.IO.ReadAllText() and another is reading text file line by line using System.IO.ReadAllLines() which returns assortment of line, and we tin loop that assortment to impress each line of text file.

Read File in .NET Framework iv.5 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 application.

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

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

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

          using System; using System.IO;  namespace ReadInCSharp {     class Program     {         static void Chief(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 cord array.

Reading text in C# all line at once

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

          using Organisation; using Organization.IO;  namespace ReadInCSharp {     class Program     {         static void Main(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 examination file. To Read text file in C# Sample.        

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

Reading Text file using StreamReader

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

StreamReader form implements a TextReader that reads characters from a byte stream in a particular encoding.

          using Organization; using System.IO;  namespace ReadInCSharp {     form Program     {         static void Main(cord[] args)         {             //file in disk             var FileUrl = @"D:\testFile.txt";              try             {                 // Create an instance of StreamReader to read from a file.                 // The using argument likewise closes the StreamReader.                 using (StreamReader sr = new StreamReader(FileUrl))                 {                     cord line;                    //read the line by line and print each line                     while ((line = sr.ReadLine()) != nil)                     {                         Console.WriteLine(line);                     }                 }             }             grab (Exception e)             {                 // Something went wrong.                 Console.WriteLine("The file could non exist read:");                 //impress error message                 Console.WriteLine(e.Bulletin);             }           }     } }                  

Output is same as to a higher place, in the abovde code, nosotros are using StreamReader case to read text from file.

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

Every bit you can see in the in a higher place code, nosotros are feeding the File url to "StreamReader" grade object and and then we are reading file line by line using sr.ReadLine(), which gives us ane line at a time from text file, then using Console.WriteLine(), we are printing the value of that line console application.

Read File in .NET Core Console application

In the above example, nosotros were reading file using .Internet framework, but you lot can too read files using 'StreamReader' in .NET Core, here is the working example.

Before, I testify you example, I have created a new console application using .Net Core in Visual Studio 2019 (Open Visual Studio -> Click on Create new project -> Select "Console App (.Internet Core)" from templates -> Click "Side by side", give your project a proper name "ReadFileInNetCore" -> Click "Create")

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

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

          using System; using Organisation.IO;  namespace ReadFileInNetCore {     class Plan     {         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()) != zilch)                 {                     //print line                     Console.WriteLine(line);                 }                                 }             Console.WriteLine("Press any key to go along");             Panel.ReadKey();         }     } }                  

If you lot volition see the above code, you will detect, there isn't any difference in C# Code, when working with .NET 4.five or .NET Core.

Output:

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

To read all files at once, you can apply "ReadAllText" as mentioned for .NET Framework "Arrangement.IO.File.ReadAllText("YourFileLocatio.txt");"

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

                      private readonly IWebHostEnvironment _webHostEnvironment;      public YourController (IWebHostEnvironment webHostEnvironment)     {         _webHostEnvironment= webHostEnvironment;     }      public IActionResult Index()     {         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 likewise like to read:

Read PDF file in C# using iTextSharp