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 have provided code sample using console application to show how to read a text file in C# line by line or reading entire text file as a string in one by go using C#.

Let's a look at each of the example code, one in which text file is read and converted into string, i.e, 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 array to print each line of text file.

Read File in .NET Framework 4.5 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 console application.

So, if you are new to C# or Visual Studio, you can create a new Console application by opening Visual Studio, navigating to "New"-> "Project" -> Select "Windows Classic" from left-pane and "Console app (Windows Application)"-> Give 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 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)
            {
                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 once

Let's take a look at C# code to read all lines at once of a text file.

using System;
using System.IO;

namespace ReadInCSharp
{
    class 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 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 particular encoding.

using System;
using System.IO;

namespace ReadInCSharp
{
    class Program
    {
        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 also closes the StreamReader.
                using (StreamReader sr = new StreamReader(FileUrl))
                {
                    string line;
                   //read the line by 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:");
                //print error message
                Console.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

As you can see in the above code, we are feeding the File url to "StreamReader" class object and then we are reading file line by line using sr.ReadLine(), which gives us one 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, we were reading file using .NET framework, but you can also read files using 'StreamReader' in .NET Core, here is the working example.

Before, I show 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 (.NET Core)" from templates -> Click "Next", 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 use the below C# Code in .NET 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
                    Console.WriteLine(line);
                }
                   
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }
}

If you will see the above code, you will notice, there isn't any difference in C# Code, when working with .NET 4.5 or .NET Core.

Output:

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

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

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

 private 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 like to read:

Read PDF file in C# using iTextSharp