C# Read Text File – Whole Content

To read a text file using C# programming, follow these steps.

  1. Import System.IO. We are going to use File class.
  2. Use File.ReadAllText() method with path to the file and encoding passed as arguments.
  3. ReadAllText() returns a string which is the whole text in the text file.

Program.cs

</>
Copy
using System.IO;
using System.Text;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            string textFileContent = File.ReadAllText(@"D:\sample.txt",Encoding.UTF8);
            System.Console.WriteLine(textFileContent);
        }
    }
}

We have used Encoding.UTF8 of System.Text to specify the encoding of the file we are reading.

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
This is C# Tutorial from www.tutorialkart.com.
This is a sample text file.

C# Read Text File – Line by Line

To read a text file line by line using C# programming, follow these steps.

  1. Import System.IO for function to read file contents.
  2. Import System.Text to access Encoding.UTF8.
  3. Use FileStream to open the text file in Read mode.
  4. Use StreamReader to read the file stream.
  5. Then we can use while loop to read each line of the text file with StreamReader.ReadLine() function.

Reading a file line by line is really useful if the size of text file is huge.

Program.cs

</>
Copy
using System.IO;
using System.Text;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            var fileStream = new FileStream(@"d:\sample.txt", FileMode.Open, FileAccess.Read);
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) {
                string line;
                while ((line = streamReader.ReadLine()) != null) {
                    System.Console.WriteLine("- "+line);
                }
            }
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
- This is C# Tutorial from www.tutorialkart.com.
- This is a sample text file.

Conclusion

In this C# Tutorial, we learned to read a file’s content as a whole and store it in a string or read the file line by line.